N
N
Nikolai2022-01-13 13:54:29
JavaScript
Nikolai, 2022-01-13 13:54:29

React Native - JSON. How to get value via API not as a list?

React Native (17.0.2) clean, no axios etc., trying to do it with fetch.

The JSON itself is an example here - https://itstav.ru/1.json

{
  "response":"success",
  "value":{
    "name":"test",
    "text":"test"
  },
  "list": [
    { "id": "1", "title": "test", "releaseYear": "1977" },
    { "id": "2", "title": "test", "releaseYear": "1977" }
  ]
}


React Native

import React, { useEffect, useState } from 'react';
import { ActivityIndicator, FlatList, Text, View } from 'react-native';

export default App = () => {
  const [isLoading, setLoading] = useState(true);
  const [data, setData] = useState([]);

  const getMovies = async () => {
     try {
      const response = await fetch('https://itstav.ru/1.json');
      const json = await response.json();
      setData(json.movies);
    } catch (error) {
      console.error(error);
    } finally {
      setLoading(false);
    }
  }

  useEffect(() => {
    getMovies();
  }, []);

  return (
    <View style={{ flex: 1, padding: 24 }}>

    {/* Тут нужно отобразить value->name */}

      {isLoading ? <ActivityIndicator/> : (
        <FlatList
          data={data}
          keyExtractor={({ id }, index) => id}
          renderItem={({ item }) => (
            <Text>{item.title}, {item.releaseYear}</Text>
          )}
        />
      )}
    </View>
  );
};


Outputs only a list from the list array , everything works as it should.

But how do I infer and display the value namefrom the object valueright after
<View style={{ flex: 1, padding: 24 }}>once before the entire list (i.e. display test)?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Ukolov, 2022-01-13
@Naraykin1998

setData(json.movies);
Rename setData to setMovies and add a state for value similar to it.
Or pass the whole json to setData, not just the list. But then you have to adapt the rest of the code to the new state format.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question