How do I add an object to a react hook?

Viewed 1562

How do I an add object to a react hook? I want to have both michael and philip stored in the state hook.

export const app = () => {
  const [state, setState] = useState({
    name: "michael",
    age: 55,
  });
  const name = "Philip";
  const age = 65;
  setState(...state, //How do I add the object with name: "Philip", age: 55 here?)
  return <div></div>;
};
2 Answers

If you want more of the same entity saved in your state you need to store that in a list - arrays in JavaScript.

Your desired state would then look like this:

const state = [
  { name: "Michael", age: 55 },
  { name: "Philip", age: 65 }
];

And the initial state like this:

const [state, setState] = React.useState([{ name: "Michael", age: 55 }]);

^ note how you wrap the object within []

To add a new person to your array you can do something like:

setState([...state, { name: "Philip", age: 65 }])

^ note how you essentially make a new array by copying everything in the previous array and also appending a new person

you could put an array of objects in the state:

const [state, setState] = useState([
  {name: "michael", age: 55}
]);

setState((arr) => [..arr, {name: "Philip", age: 55}])

or if you wanted to have a default state with an empty array instead:

const [state, setState] = useState([]);
// ...
setState((arr) => [..arr, {name: "michael", age: 55}])
setState((arr) => [..arr, {name: "Philip", age: 55}])

Whenever you call the setState function with an anonymous object the first parameter will always contain the current state, which is in your case an array of {name: string, age: number} objects. The return value of that anonymous function will return a new array with the a object and the existing objects:

setState((arr) => [
  ...arr, // existing objects
  {name: "Philip", age: 55} // new object
])

you could also set the new state directly without using a reducer (the anonymous functions in the examples above)

setState([
  ...state, // existing objects
  {name: "Philip", age: 55} // new object
])

but this could cause some problems when dealing with asynchronous code (a stale state could be copied into the new state).

Related