Ulugbek
Ulugbek

Reputation: 147

How to update the object key's value in state using useState() hook?

I have a array of objects state that has two key-value pairs [{name: 'Max', value: 1}]

when updating the state i am receiving the name from api and comparing with api.name == state.name. if it is true i need to update the value like value + 1. How do i achieve with setState()?

Upvotes: 0

Views: 4160

Answers (3)

zeeshan zahoor
zeeshan zahoor

Reputation: 77

You can update the value as:

//for example below data is coming from api

const array1 = [{ name: "Zee" }, { name: "Zee" }, { name: "Zee" }];

//Your state for updating value based on name

const [data, setData] = useState({ name: "Zee", value: 1 });

//check is name exist in api data or not if it exist it will increment the value

array1.map((item) => {
    if (item.name === data.name) {
      setData({ ...data, value: data.value + 1 });
    }
  });



console.log("check=", data);

Upvotes: 0

Soufiane Boutahlil
Soufiane Boutahlil

Reputation: 2604

You could update the state like this:

    const stateUpdated = state.map((item) => {
      if (name === item.name) {
        return {
          ...item,
          value: ++item.value,
        };
      } else {
        return item;
      }
    });

    setState(stateUpdated);

Upvotes: 0

ldruskis
ldruskis

Reputation: 799

You could use spread operator, to update the state by only changing the object properties.

this.setState({ array: this.state.array.map((item) => {
  const condition = "..."; // Implement logic
  return {...item, value: condition ? item.value + 1 : item.value }
 })
})

Upvotes: 1

Related Questions