I'm trying to setState using the rule that state should not be mutated but I keep getting an error. Can't figure this out.
Here is my state:
this.state = {
jsonReturnedValue: null,
fruit: [
{
id: 1,
title: 'Orange',
selected: false,
key: 'fruit'
},
{
id: 2,
title: 'Grape',
selected: false,
key: 'fruit'
},
{
id: 3,
title: 'Pomegranate',
selected: false,
key: 'fruit'
},
{
id: 4,
title: 'Strawberry',
selected: false,
key: 'fruit'
}
]
}
I do a fetch when component mounts with:
componentDidMount() {
fetch('http://127.0.0.1:8000/api/printing/postcards-printing')
.then(response => response.json())
.then(json => {
this.setState({ jsonReturnedValue: [...this.state.jsonReturnedValue, json.printCategory.products] }, () => console.log(this.state));
});
}
This returns the error: Uncaught (in promise) TypeError: Cannot convert undefined or null to object
The following works
.then(json => {
this.setState({ jsonReturnedValue: json.printCategory.products }, () => console.log(this.state));
});
However the working one would mutate the state which according to what I've read is a bad practice. Any help would be greatly appreciated!
[...null]
that causes an error. so either innitializejsonReturnedValue: []
or make a check ifjsonReturnedValue
is not array yet – skyboyer[...this.state.jsonReturnedValue, ...json.printCategory.products]
– Alexander Staroselsky