shorif
shorif

Reputation: 71

I'm fetching a problem when I'm trying to fetch data from an API by using useEffect in react

const [users, setUsers] = useState([]);
const getUsers = async () => {
    const URL = "https://jsonplaceholder.typicode.com/users";
    const response = await fetch(URL);
    const data = await response.json();
    console.log(data); // return 10 array . 
    setUsers(data);
    console.log(users); // return empty Array 
};
useEffect(() => {
    getUsers();
}, []);

when I run this code and reload the browser, the data variable shows 10 arrays (that's what I expected) and the users state doesn't return an empty array (that's the problem). And then I'm changing something on code, and come to the browser, data variable and users state both shows 10 arrays. That means I'm trying to tell you that, when I'm reloading the browser for the first time state doesn't set from data variable . See the console result to better understand

Upvotes: 1

Views: 275

Answers (1)

bonnopc
bonnopc

Reputation: 850

Setting a state is an asynchronous process. That's why you won't see the immediate effect after calling the setUsers(). Rather you can add another useEffect in your code and see the changes happening for users

// ... other code
useEffect(() => {
    // this will run after the 'users' has been changed
    console.log("Users", users)
}, [users]);
// ...

After adding this useEffect you will see that the users will be printed after it is updated.

Upvotes: 3

Related Questions