0
votes

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!

1
since ` jsonReturnedValue: null,` your code is trying to [...null] that causes an error. so either innitialize jsonReturnedValue: [] or make a check if jsonReturnedValue is not array yetskyboyer
That was it! Now my only thing is that I have jsonReturnedValue->array[0]->array[3] so it's adding another array into the array. How can I make it just push the array? @skyboyerFabricioG
[...this.state.jsonReturnedValue, ...json.printCategory.products]Alexander Staroselsky

1 Answers

0
votes

You are trying to spread a null primitive, which is not possible. So instead do this with your initial state:

this.state = {
  jsonReturnedValue: [],
  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'
    }
  ]
};

Also note that you're going to want to do this { jsonReturnedValue: [...this.state.jsonReturnedValue, ...json.printCategory.products] }. Note the spread in the second index of the array.