0

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"
    }]
}
Dylan
  • 836
  • 1
  • 10
  • 24
Rohullah Rajaee Rad
  • 552
  • 2
  • 8
  • 28

2 Answers2

1

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

dungmidside
  • 508
  • 7
  • 19
0

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 }));
Steric
  • 266
  • 4
  • 10