0

I'm trying to save State twice, so I can reset it later on, but no matter what method I try, the 'setFullTrials' won't update with the saved data. The "console.log(savedData)" shows that all the data is there, so that's definitely not the problem. Not sure where I'm going wrong.

function AllTrials({Trialsprop}) {
        let [savedData, setSavedData] = useState([]);
        let [fullTrials, setFullTrials] = useState([]);
        useEffect(() => {
          //Call the Database (GET)
            fetch("/trials") 
              .then(res => res.json())
              .then(json => {
                // upon success, update trials
                console.log(json);
                setFullTrials(json);
                setSavedData(json);
              })
              .catch(error => {
                // upon failure, show error message
              });
          }, []);
          


    const resetState = () => {
          setFullTrials(savedData);
          //setFullTrials((state) => ({
            ...state,
            savedData
          }), console.log(fullTrials));
          // setFullTrials(savedData.map(e => e));
          console.log("savedData", savedData)
      }
Konrad
  • 21,590
  • 4
  • 28
  • 64
Morella
  • 3
  • 2
  • 2
    How do you know that the fullTrials is not updated? – grekier Aug 15 '22 at 11:28
  • Where do you call `resetState`? Showing the full code would be helpful – Angshu31 Aug 15 '22 at 11:30
  • Your code works fine: https://codesandbox.io/s/serverless-grass-ov9xdf?file=/src/App.js The only "problem" is that you're logging the updated state too early since state changes are asynchronous –  Aug 15 '22 at 11:33
  • Duplicate: [Why does calling react setState method not mutate the state immediately?](https://stackoverflow.com/questions/30782948/why-does-calling-react-setstate-method-not-mutate-the-state-immediately) –  Aug 15 '22 at 11:33
  • Thanks @ChrisG I'm new to React and have only used the functional component way of doing things, not the class component so I did read that duplicate but didn't fully understand it. – Morella Aug 15 '22 at 12:25
  • It works the same – Konrad Aug 15 '22 at 12:27
  • Yeah, class/functional doesn't really matter; updates to a state are batched and executed soon in the future, not immediately. Logging a state right after setting it will show the old value. The best way to look at state during debugging is to add `
    {JSON.stringify(someStateVar, null, 2}
    ` to your component, this will always show the current state right in your browser.
    –  Aug 15 '22 at 12:34

1 Answers1

0

Setting the state in React acts like an async function.
Meaning that the when you set the state and put a console.log right after it, it will likely run before the state has actually finished updating.

Which is why we have useEffect, a built-in React hook that activates a callback when one of it's dependencies have changed.

Example:

useEffect(() => {
   console.log(fullTrials)
   // Whatever else we want to do after the state has been updated.
}, [fullTrials])

This console.log will run only after the state has finished changing and a render has occurred.

  • Note: "fullTrials" in the example is interchangeable with whatever other state piece you're dealing with.

Check the documentation for more info.

P.S: the correct syntax for useState is with const, not let.
i.e. - const [state, setState] = useState()

tomleb
  • 2,409
  • 2
  • 9
  • 24
  • Please check for duplicates before posting answers. 99.9% of JavaScript questions are dupes (or typos) –  Aug 15 '22 at 11:39