Rohullah Rajaee Rad
Rohullah Rajaee Rad

Reputation: 581

how to append object array to current state in react functional component

this is my state

const [dataItem, setDataItem] = useState({
    id: null,
    code: null,
    title: null,
    prent: null,
    unitId: null,
});

and i want append file to dataItem state

let file = [
    {
        uid: '1',
        name: items.file,
        status: 'done',
    },
];
setDataItem({ ...dataItem, file });

but it instead of append to dataItem , it replaced and other elements(e.g id, code, title) will be null dataItem state after append file

{
    "id": null,
    "code": null,
    "title": null,
    "prent": null,
    "unitId": null,
    "file":[{
        "uid": "1",
        "name": "u104.svg",
        "status": "done"
    }]
}

Upvotes: 0

Views: 6314

Answers (2)

Steric
Steric

Reputation: 415

To append file keeping the previous state intact, you'll need to use functional updates.

let file = [
  {
    uid: '1',
    name: items.file,
    status: 'done',
  },
];
setDataItem(prevState => ({ ...prevState, file }));

Upvotes: 0

dungmidside
dungmidside

Reputation: 518

Because the state was initialized to an object instead of an array. It should be

const [dataItem, setDataItem] = useState([{
    id: null,
    code: null,
    title: null,
    prent: null,
    unitId: null,
}]);

When update dataItem, you have to spread array file too

setDataItem({ ...dataItem, ...file });


Read more => Correct modification of state arrays in ReactJS

Upvotes: 1

Related Questions