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)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs