Home > OS >  Read Json data that have nested array in react native
Read Json data that have nested array in react native

Time:01-14

I have Json data and want to read genre data specially name key using Native Base. Here is my Json, I got it from TMDB API

the genres key using nested array to store the data

"genres": [
    {
      "id": 878,
      "name": "Science Fiction"
    },
    {
      "id": 12,
      "name": "Adventure"
    },
    {
      "id": 28,
      "name": "Action"
    }
  ],

I am trying to load data from API like this

fetchDetails = () => {
    fetch(
      `https://api.themoviedb.org/3/movie/${movie_id}?api_key=9b68fedd9d8cacc97e967403feb9d5fc`
    )
      .then((response) => response.json())
      .then((json) =>
        this.setState({
          contentGenre: json.genres[0]
        })
      )
      .catch((error) => console.error(error))
      .finally(() =>
        this.setState({
          isCategoriesLoading: false,
        })
      );
  };

And I'm trying to display the genre like this, but the data isn't showing

<Text>{contentGenre.name}</Text>

Thanks for your help!

CodePudding user response:

Not really sure what the issue is. The following code works and prints Drama at the console. I used a fixed value (345) for the movie id. Perhaps you should remove your API key from the question.

fetch( https://api.themoviedb.org/3/movie/345?api_key=9b68fedd9d8cacc97e967403feb9d5fc ) .then((response) => response.json()) .then((json) =>( console.log(json.genres[0].name) ) ) .catch((error) => console.error(error)) .finally(() => console.log("Done") );

CodePudding user response:

Here is how to access the name of the first genre.

fetch(`https://api.themoviedb.org/3/movie/${movie_id}?api_key=...`)
  .then((response) => response.json())
  .then((json) => json["genres"][0].name)
  .then(console.log)
  • Related