skip to Main Content

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.

3

Answers


  1. Try Updating your useEffect like this –

    useEffect(() => {
       getData();
       getDataDetails();
    }, []);
    

    [] dependency array in useEffect will run the effect on component mount.

    Login or Signup to reply.
  2. /* 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.

    Login or Signup to reply.
  3. 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;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search