Home > Software engineering >  Resetting State in React with saved initial State
Resetting State in React with saved initial State

Time:08-15

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)
      }

CodePudding user response:

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()

  • Related