0

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.

user14232549
  • 405
  • 4
  • 17

2 Answers2

0

For both variable as array so you need spread both inside the array

like

[...prev,...new]

Your case better use setState callback

this.setState(state => {
  state.suggestions = [...state.suggestions, ...[{
    id: "India",
    text: "India"
  }]]
  return state
});
prasanth
  • 22,145
  • 4
  • 29
  • 53
0

You are logging just below the setting state, which is async actually..

please try this

this.setState( {testarray: setCountries},()=>{
       console.log(this.state.testarray)
});
Hrishi
  • 1,210
  • 1
  • 13
  • 25