Home > Mobile >  changing multiple state value - react
changing multiple state value - react

Time:06-22

I have a state object that represents rows and columns that looks something like this.


  const [state, setState] = useState([
    { firstName: "example", lastName: "example", petName: "example" },
    { firstName: "example", lastName: "example", petName: "example" },
    { firstName: "example", lastName: "example", petName: "example" },
  ]);

how can I set my state to change the key of all the petName values whilst keeping the original state?

CodePudding user response:

You can use map and spread operator:

const [state, setState] = useState([
    { firstName: "example", lastName: "example", petName: "example" },
    { firstName: "example", lastName: "example", petName: "example" },
    { firstName: "example", lastName: "example", petName: "example" },
  ]);

{...}

const changePetNames = (newValue) => setState(state => state.map(obj => {...obj, petName: newValue}))

CodePudding user response:

const [data, setData] = useState([
  {
    id:   1,
    name: 'john',
    gender: 'm'
  }
  {
    id:   2,
    name: 'mary',
    gender: 'f'
  }
]);

const updateField = (index) => (e) => {
  let newArr = [...data];
  newArr[index] = e.target.value;
  setData(newArr);
}

CodePudding user response:

You can use a Array.map() to change all the values as it's an array:

console.log([{
    firstName: "example1",
    lastName: "example1",
    petName: "example"
  },
  {
    firstName: "example2",
    lastName: "example2",
    petName: "example"
  },
  {
    firstName: "example3",
    lastName: "example3",
    petName: "example"
  },
].map((p, i) => ({
  ...p,
  petName: "New Name "   (i   1)
})));

CodePudding user response:

Here's a simple way to do it. This will keep the value of the key just update the name.

setState((prevState) =>
      prevState.map((state) => {
        state["newKey"] = state.petName;
        delete state["petName"];
      })
    );
  • Related