krisyupher
krisyupher

Reputation: 13

access the data of a hook- React

I am requesting this API, then I save the result in the "data" hook. when I want to print "data.total_results" everything ok but when I want to print a key that has more data inside it doesn't leave me "Data.results [0] .title"

import React, { useState, useEffect } from 'react';

const Movie = () => {
  // Declara una nueva variable de estado, que llamaremos "count".
  const [Data, setData] = useState("");

  useEffect(() => {
    const Cargar = async () => {
      let respuesta = await fetch("https://api.themoviedb.org/3/discover/movie?api_key=ce322f54257cc9286282b320c5e9b2a0&language=en-US&sort_by=popularity.desc&include_adult=false&include_video=false&page=1");
      let respuestaJSON = await respuesta.json();
      setData(respuestaJSON);
    };
    Cargar();
  }, [Data]);
  return (
    <div>
      {Data.total_results}
      {/* {Data.results[0].title} */}
    </div>
  );
}

export default Movie;

Upvotes: 1

Views: 104

Answers (3)

Jayakumar Thangavel
Jayakumar Thangavel

Reputation: 2007

const [Data, setData] = useState([]);

import React, { useEffect, useState } from 'react';
import axios from 'axios';
import ReactTable from 'react-table'
import 'react-table/react-table.css'
const Movie = () => {
  // Declara una nueva variable de estado, que llamaremos "count".

const [Data, setData] = useState([]);
   useEffect(() => {
    axios.get("https://api.themoviedb.org/3/discover/movie?api_key=ce322f54257cc9286282b320c5e9b2a0&language=en-US&sort_by=popularity.desc&include_adult=false&include_video=false&page=1")
      .then(function(response) {
               console.log(response.data.results)
        setData(response.data.results);

      }).catch(function(error) {
        console.log(error);
      })
  }, []);

  return (<div>
  {Data.map(function (row, i) {  
        return <div key={i}>
        {row.title} 
     </div>
   })}
 </div>)      
}

export default Movie;

Upvotes: 0

jogesh_pi
jogesh_pi

Reputation: 9782

You need to check if the results property is defined.

<div className="App">
  <h1>Total {Data.total_results}</h1>
  {typeof Data.results !== "undefined" &&
    Data.results.map((movie, index) => {
      return <h3>{movie.title}</h3>;
    })}
</div>

Working Demo: https://codesandbox.io/s/distracted-feather-4l55r

A few days back, I have created a repository and implemented OMDB API with React. This may help you.

https://github.com/jogeshpi03/omdb-react

Upvotes: 1

Sparragus
Sparragus

Reputation: 913

Your code is almost right. There's a bug and a couple improvements you can make.

First let's take a look at the useEffect hook.

useEffect takes two arguments: a function, and a list of dependencies. The first time the component is rendered, and when any of the dependencies change, the function argument will be executed again.

So right now you have a bug with your dependencies that is causing an infinite loop. When the component is rendered, you execute the function in useEffect. That function will eventually set Data. When the value for Data is set, that will cause the useEffect function to be executed again. Which will set a new value to Data, which will execute the function again, ad infinitum.

The fix is to set the dependencies to [] if you only want that to run once. Like this:

  useEffect(() => {
    const Cargar = async () => {
      let respuesta = await fetch("https://api.themoviedb.org/3/discover/movie?api_key=ce322f54257cc9286282b320c5e9b2a0&language=en-US&sort_by=popularity.desc&include_adult=false&include_video=false&page=1");
      let respuestaJSON = await respuesta.json();
      setData(respuestaJSON);
    };
    Cargar();
  }, []); // <-------- This changed to []

I hope that fixes your issue.

Now I will suggest some improvements:

I would set the initial state of Data to undefined

  const [Data, setData] = useState();

and then use a conditional in the JSX like so

if (!Data) {
  return <div>Loading...</div>
}

return (
  <div>
    {Data.total_results}
  </div>
);

Upvotes: 1

Related Questions