Lineesh Mb
Lineesh Mb

Reputation: 77

useState Object not updating properly

When we try to update useState object properties simultaneously. its not updating.

const [stateData, setStatedata] = useState({
id: 0,
name: '',
address: '',
street: '',
city: '',
country: '',
property1: '',
property2: ''
etc...
});

When I try to update property1 on a text change event

const test = () => {
if(case == 1){
setStatedata({
 ...stateData,
 property1: '123'
});
}
else{
// Do something
}
setStatedata({
 ...stateData,
 property2: '654'
});
}

In this case property1 value will not be set to 123.

But its not waiting for property1 value to be updated. The previously updated value isn't always there.

If I need 20 or more state properties, which is better solution?

  1. Object
  2. A single state for each property

Upvotes: 0

Views: 3487

Answers (3)

Dmitriy Mozgovoy
Dmitriy Mozgovoy

Reputation: 1597

You should update the state value in the following way:

setStatedata(state=> ({
   ...state,
   property2: '65554'
}));

In addition, you can use a custom hook from my lib that implements a deep state manager (Live Demo):

import React from "react";
import { useAsyncDeepState } from "use-async-effect2";

function TestComponent(props) {
  const [state, setState] = useAsyncDeepState({
    x: 123,
    y: 456
  });

  const incX = () => {
    setState(({ x }) => ({ x: x + 1 }));
  };

  const incY = () => {
    setState(({ y }) => ({ y: y + 1 }));
  };

  return (
    <div className="component">
      <div className="caption">useAsyncDeepState demo</div>
      <div>state.x : {state.x}</div>
      <div>state.y : {state.y}</div>
      <button onClick={() => incX()}>Inc X</button>
      <button onClick={() => incY()}>Inc Y</button>
    </div>
  );
}

If using in the context of async code and you need to wait for updates Live Demo

import React, { useCallback, useEffect } from "react";
import { useAsyncDeepState } from "use-async-effect2";

const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

function TestComponent(props) {
  const [state, setState] = useAsyncDeepState({
    counter: 0,
    computedCounter: 0
  });

  useEffect(() => {
    setState(({ counter }) => ({
      computedCounter: counter * 2
    }));
  }, [state.counter]);

  const inc = useCallback(() => {
    (async () => {
      await delay(1000);
      await setState(({ counter }) => ({ counter: counter + 1 }));
      console.log("computedCounter=", state.computedCounter);
    })();
  });

  return (<button onClick={inc}>Inc</button>);
}

Upvotes: 2

Maxx P
Maxx P

Reputation: 176

You should pass two parameter text change event click.

  1. Object property name that you want to change in state object. ex:- property1
  2. Value that you want to set for that Object property.ex:- Any value(text event value)

And your test function like this

const test = (key,value) => {
    setStatedata({...stateData,[key]:value})
}

Now you don't need to create multiple functions to change object values.

Upvotes: 0

H9ee
H9ee

Reputation: 420

i try this code work for me you can try this: codesandbox

 const [stateData, setStatedata] = useState({
    id: 0,
    name: '',
    address: '',
    street: '',
    city: '',
    country: '',
    property1: '',
    property2: ''
    });
    
   const test = () => {
    setStatedata({
      ...stateData,
      property1: '123'
     });
  
   }
   const test2 = () => {
   
     setStatedata({
      ...stateData,
      property2: '65554'
     });
   }
   console.log(stateData)
  return (
    <div className="App">
      <h1 onClick={() => test()}>Click Here</h1>
      <hr />
      <h1 onClick={() => test2()}>Click Here2</h1>
      <h2></h2>
    </div>
  );

Upvotes: 0

Related Questions