Home > Software engineering >  usestate not setting the data
usestate not setting the data

Time:10-21

i am using usestate for transfer data. but ufotunately it not quite work.

here is my code:

const [totCons, settotCons] = useState(null)
     useEffect(() => {
        // declare the async data fetching function
        const fetchData = async () => {
          // get the data from the api
          const data = await fetch('https://piscons2.vercel.app/ConsPiscTotCons');
          // convert the data to json
          const json = await data.json();       
          // set state with the result
          settotCons(json);
          console.log(json)
          console.log(totCons)
        }  
        // call the function
        fetchData()
          // make sure to catch any error
          .catch(console.error);;
      }, [])

as you can see on image the json return data but the totCons return null. i did set it settotCons(json)

enter image description here

CodePudding user response:

Updated state will not be available to the state value immedieately.

The react setState is asynchronous, but thats not the only reason for this behaviour. The reason is a closure scope around an immutable const value.

Both props and state are assumed to be unchanging during 1 render.

Treat this.state as if it were immutable.

You can use useEffect to create the sideeffects for totCons

useEffect(() => {
    // action on update of totCons
}, [totCons]);

CodePudding user response:

try doing console.log(totCons) outside useEffect. you will not get the updated value in next line. you will get the updated value in next render

  • Related