DEV Community

Ryan Bowlen
Ryan Bowlen

Posted on

React Hooks: Initial State of Object Pitfall

Recently I ran into an issue with React Hooks where an API call was failing because the steps I needed to complete were encountering some unintended consequences.

I wanted an object to represent a series of steps that needed to be completed one-at-a-time.


const [stepComplete, setStepComplete] = useState({ 
     stepOne: false,
     stepTwo: false,
     stepThree: false,
});
Enter fullscreen mode Exit fullscreen mode

The issue occurred with the way that I was setting the step. I needed to everything the same except for the step I was editing. I had to search around for some time and follow some trial-by-error until I figured out what to do. These were all fruitless approaches:

//Nope
setStepComplete.stepOne(true),
//Doesn't update the whole object and so no re-render!
setStepComplete(stepOne: true),
//This deleted the rest of the Object!
setStepComplete(...setStepComplete, stepOne: true)
Eventually I thought to destructure the object through the use of an arrow function:

setStepComplete(state => ({...state, stepOne: true}));
Enter fullscreen mode Exit fullscreen mode

And voila! My code was working perfectly!

Discussion (0)