0

This is probably a super simple question but I seem to be finding various answers to. Essentially I have an app that makes an axios call to get a list of items via JSON API.

I need to set the initial state on the component load my state looks like this:

this.state = {
  sensors: [],
  filterName: "",
  sortBy: "id",
};

my component loading code looks like so:

  componentDidMount =() => {
    axios
      .get("http://localhost:3000/api/v1/devices.json")
      .then((response) => {
        // handle success
        console.log(response);
        this.setState({ sensors: [...response.data]});
      })
      .catch((error) => {
        console.log(error);
      })
  }

This works...but I feel like this isn't the right way. Isn't it not supposed to change the initial array because I remember reading that we shouldn't ever be changing the initial state only returning a new version of it?

Is there a better/safer way?

(Also what about updating a single one/adding an item to array of objects? Is there a "preferred way")

1 Answer 1

1

If you are looking to add elements to the sensors array without directly mutating the state, this is what you can do.

const { sensors } = this.state;
this.setState({ 
  sensors: [...sensors, response.data]
});

What this does is that we are using the spread syntax to destructure the array, and copy it to a new array with the response.data from the API.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.