I'm trying to set state while adding a key value to the array. I've followed several questions including this one: How to add a new key value to react js state array?
I can't get any of those answers to work with my challenge.
My state is like this:
this.state = { jsonReturnedValue: [] }
when componentDidMount() I make a fetch request and I added new state and a foreach loop (as based on the instructions from the question above)
componentDidMount() {
let newState = [...this.state.jsonReturnedValue];
newState.forEach(function(file) {
file.selected = "false"
})
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));
})
.then(this.setState({jsonReturnedValue: newState}, () => console.log("selected added" + this.state) ));
}
I was thinking that I would just setState again with the key value pair so I added the .then the third time but it's not working.
the final console log returns this: selected added[object Object]
Digging more into it I see the object is empty.
EDIT: My goal is to set the state with the api call but also add key value of "selected: false" to each array.