how to push an element using a useState in a specific key nested?

I need to do a push on my setMiObj but I don't know how to do something like setMiObj.numbers.push(123):

my output desired:

{ numbers: [22,123],name:"John Doe" }

how can I do it?

import "./styles.css";
import React, { useEffect, useState } from "react";
export default function App() {
  const [miObj, setMiObj] = useState({ numbers: [22],name:"John Doe" });
  return (
    <div className="App">
    </div>
  );
}

Solution 1:

You can just do something like

setMiObj({...miObj,numbers:[...miObj.numbers,123]})

If you want different people I would store the state as an array of objects. So every object would be { numbers: [],name:"John Doe" }. Your code would look like this :

const [miObj, setMiObj] = useState([{ numbers: [],name:"John Doe" }]);

instead of this

const [miObj, setMiObj] = useState({ numbers: [],name:"John Doe" });

Notice the [] surrounding the object.

Now that you have an array of objects, you can leverage the ... operator to do this. It's pretty clean. Let's say the state already has something like this [{ numbers: [123],name:"John Doe" }] and you want to append Jane's so it would like this { numbers: [123],name:"John Doe" }

Here's what it would look like:

setMiObj([...miObj,{"numbers" : [214], "name":"Jane Smith"}])

The ... will expand all the previous state objects and also add Jane Smith's object to it!