Dimisizz
Dimisizz

Reputation: 69

Get value from fetch in React

I try to pass an array of object from localhost:5000/users to Table component as a prop but I can't.

I can fetch data from localhost:5000/users and when I try to do console.log inside it, I can see data. But when I try to do console.log outside fetch function, it returns an empty array.

The question is how can I pass the data to Table component if the data is not visible outside the fetch function ?

import React from 'react';
import './App.css';
import Table from './Table';

function App() {

    let obj = [];

    fetch('http://localhost:5000/users')
    .then((response) => {
        return response.json();
    })
    .then((data) => {
        return obj = data;
    })
    .then(() => {
        console.log(obj); // Here it returns correct data from localhost:5000/users
        return obj;
    });

    console.log(obj); // But right here, it returns an empty array

    return (
        <div>
            <Table data={obj} /> {/* The question is how can I pass data from localhost:5000/users to Table component ? */}
        </div>
    )
}

export default App;

Upvotes: 1

Views: 2200

Answers (3)

George Tibetegya
George Tibetegya

Reputation: 126

I think this is happening because the fetch API call is a promise, therefore, the second console.log console.log(obj); // But right here, it returns an empty array runs before the promise resolves.

You can use state and useEffect as mentioned by Rahul Amin. I have created a js fiddle you can checkout. here. https://jsfiddle.net/titbetegya/owk7eg2a/18/

Upvotes: 0

Ruhul Amin
Ruhul Amin

Reputation: 1779

You need to use state and useEffect state in React.js . I would recommend to invest more time on useState and useEffect. To do so React.js official documentation is good source to study. Here is also some resource links: how to use useState how to use useEffect


import React, {useState} from 'react';
import './App.css';
import Table from './Table';

function App() {

    const [obj, setObj] = useState([])

      useEffect(() => {
        fetch("http://localhost:5000/users")
          .then((response) => {
            return response.json();
          })
          .then((data) => {
            //return obj = data;
            setObj(data); // setting obj using setObj
          })
          .then(() => {
            console.log(obj); // Here it returns correct data from localhost:5000/users
            return obj;
          });
      }, []);


    console.log(obj); // But right here, it returns an empty array

    return (
        
             {/* The question is how can I pass data from localhost:5000/users to Table component ? */}
        
    )
}

export default App;

Upvotes: 1

RaeperFR
RaeperFR

Reputation: 27

A solution can be : Create a state inside a constructor in your class.

Now when you fetch, setState the data inside your state :)

Now if you create a function outside your fetch it can be like this

onClick = () => {
   console.log(this.state.data)
}

Now, you can do what you want with your data on all your component :) And if you want to use the same component for many data, your state need to be an array, and you need to map your state :)

Have fun

Upvotes: 0

Related Questions