0

I am new to React. I am setting the state after fetching data from server. When I am trying to get that data from the state I am always getting null.

const [data, setData] = useState(dataObj); 

const getData = () => {
   //Fecthing data from server
   setData(data);
}

useEffect(() => {
   getData();
   getDataDetails();
}

in getDataDetails() I need the properties from state (data) which is always null.

const getDataDetails = () => {
   console.log(data.empId);
}

How can make sure that state is always updated. How can I achieve it.

ppb
  • 2,299
  • 4
  • 43
  • 75
  • 1
    This is the second most common type of React question (the first is questions about async data loading). The state is getting updated in the next render. There are hundreds of exact duplicates of this question on SO. [React setState not updating state](https://stackoverflow.com/questions/41446560/react-setstate-not-updating-state) – Andy Ray Jun 14 '23 at 23:34
  • Adding onto the comment by Andy. If you cannot wait until next render, then make `getDataDetails` depend directly on the retrieved data. `const apiData = getData(); getDataDetails(apiData)` kind of approach, instead of relying only in the react state can be one way to do it. – Jhilton Jun 14 '23 at 23:45

2 Answers2

0
/* Comment 1. data initialized here */
const [data, setData] = useState(dataObj); 

/* Comment 3. maybe you might be fetching from server buthere you are setting the same data object that you have got after useState call. Since reference to data is not changing it will not re render the component 
*/

const getData = () => {
   //Fecthing data from server  --- // 3.1 But you are setting same data object returned from useState
   setData(data);
}

useEffect(() => {
   getData();
   getDataDetails();
})
/* Comment 2. I assume you have closed the bracket with or without dependency array.
    */

Please go through the comment 1, 2, 3. The main problem with the code here is that we are assigning the same data and not the new object to setData. it will not cause rerender.

Amit Chauhan
  • 221
  • 2
  • 11
0

This is a complete example of a useState in react with fetch

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

const RickAndMortyAPI = () => {
  const [characters, setCharacters] = useState([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    fetch('https://rickandmortyapi.com/api/character/')
    .then(response => response.json())
    .then(data => {
     setCharacters(data.results);
     setLoading(false);
    })
    .catch(error => console.error(error));
  }, []);

 if(loading){
   return <div>Loading...</div>;
 }

return (
  <div>
    <h1>Rick and Morty characters</h1>
    <ul>
      {characters.map((character) => (
        <li key={character.id}>
          <h2>{character.name}</h2>
          <img src={character.image} alt={character.name} />
          <p>Status: {character.status}</p>
          <p>Species: {character.species}</p>
        </li>
      ))}
    </ul>
  </div>
);
};

export default RickAndMortyAPI;