Home > Mobile >  pushing object to array in reactjs?
pushing object to array in reactjs?

Time:03-23

i have a problem with pushing object to array.. i want a result like this.. [{b:"a"},{b:"c"}]

with this code

const [list, setList] - useState({occupation_id: ""});

const handleAdd = () => {
    let arr = [];
    const newData = {...list};
    newData[e.target.id] = e.target.value;
    arr.push(newData);
    setList(arr);
}

but the result from the code below is

[{{occupation_id: "2"}, occupation_id: "1"}]

what the problem with my code?

CodePudding user response:

You can solve it easily with this solution, Try this:

const [list, setList] = useState([]); // your initial data
const handleAdd = () => {
 setList([...list, {e.target.id:e.target.value}]);
}

CodePudding user response:

Try this :

const [list, setList] = useState([]);
const handleAdd = () => {
 setList([...list, {[e.target.id]:e.target.value}]);
}

CodePudding user response:

const [list, setList] = useState([{occupation_id: "1"}, {occupation_id: "2"}]);

  const handleAdd = (id, value) => {
    const newData = [...list]  
    newData.push({id, value});
    setList(newData);
    console.log(newData)
}

CodePudding user response:

**Define state like an array: this works**

const [list, setList] = useState([{occupation_id: "2"}]);

const handleAdd = (e) => setList([...list, { e.target.name: e.target.value }])
  • Related