I tried this Correct modification of state arrays in React.js
Correct modification of state arrays in React.js
any elements have not added to the array.
[...array,[{},{}]] and
this.state.aaaa.concat[newArray] are invalid for my code. I would like to set a JSON-array to a state but it does not work.
const setCountries = COUNTRIES.map((country) => {
console.log("OMG!");
return {
id: country,
text: country,
};
});
class Stack extends Component {
constructor(props) {
super(props);
this.state = {
testarray: [],
};
this.setState( {testarray: setCountries});
console.log("MO"+JSON.stringify(setCountries))
console.log("UU"+JSON.stringify(this.state.testarray))
Console says. MO
MO[{"id":"Afghanistan","text":"Afghanistan"},{"id":"Albania","text":"Albania"},{"id":"Algeria","text":"Algeria"},{"id":"Andorra","text":"Andorra"},{"id":"Angola","text":"Angola"},{"id":"Anguilla","text":"Anguilla"},{"id":"Antigua & Barbuda","text":"Antigua & Barbuda"},{"id":"Argentina","text":"Argentina"},{"id":"Armenia","text":"Armenia"},{"id":"Aruba","text":"Aruba"},{"id":"Australia","text":"Australia"},{"id":"Austria","text":"Austria"},{"id":"Azerbaijan","text":"Azerbaijan"},{"id":"Bahamas","text":"Bahamas"},{"id":"Bahrain","text":"Bahrain"},
UU[]
The other way
constructor(props) {
super(props);
this.state = {
suggestions: [{ id: "Thailand", text: "Thailand" }],
};
this.setState( {suggestions: [{ id: "India", text: "India" }] } );
this.setState( {suggestions: [...this.state.suggestions,[{ id: "India", text: "India" }]] } );
was also invalid.
The result is UU[{"id":"Thailand","text":"Thailand"}]... India was not set.