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"
    }]
}
1
  • 2
    What is the expected output after append file to dataItem state? Commented Apr 4, 2020 at 7:42

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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 }));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.