DEV Community

Ryan Bowlen
Ryan Bowlen

Posted on

1 1

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!

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay