0

I'm trying to change the state of only one specific array item from the reviews array. How can this be done? This code doesn't seem to work:

this.setState({
  reviews[2].current: true
});

Here's the full code:

import React, { Component } from "react";
import { render } from "react-dom";

const reviewsInit = [
  {
    name: "Peter Lahm",
    current: null
  },
  {
    name: "Simon Arnold",
    current: null
  },
  {
    name: "Claire Pullen",
    current: null
  }
];

class App extends Component {
  constructor() {
    super();
    this.state = {
      name: "React",
      reviews: reviewsInit
    };
  }

  change = () => {
    this.setState({
      reviews[2].current: true
    });
  };

  render() {
    return (
      <div>
        {console.log(this.state.reviews[2].current)}
        <button onClick={this.change}>click me</button>
      </div>
    );
  }
}

render(<App />, document.getElementById("root"));

Demo: https://stackblitz.com/edit/react-tbryf5

As you can probably tell I'm new to react! Thanks for any help here

3 Answers 3

2

For some context, React detects state change when reference of the state object changes. It does not track deep changes happening in array or the object.

Solution

We need to make another variable with same data (mostly destructuring). Change the value needed. And assign that to state again.

For Object

this.setState({...oldState, keyToChange: 'newValue'});

For Array

const temp = [...oldState];
temp[index] = 'newValue';
this.setState(temp);

Hope it helps.

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

Comments

1

It's common for an Array state to copy first then update one of its value

  change = () => {
    const result = [...this.state.reviews];
    result[2].current = true;
    this.setState({reviews: result});
  };

Comments

1
import React, { Component } from "react";
import { render } from "react-dom";

const reviewsInit = [
{
    name: "Peter Lahm",
    current: null,
},
{
    name: "Simon Arnold",
    current: null,
},
{
    name: "Claire Pullen",
    current: null,
},
];

class App extends Component {
constructor() {
    super();
    this.state = {
        name: "React",
        reviews: reviewsInit,
    };
}

change = () => {
    const prevState = [...this.state.reviews];
    prevState[2].current = true;
    this.setState({
        reviews: prevState,
    });
};

render() {
    return (
        <div>
            {console.log(this.state.reviews[2].current)}
            <button onClick={this.change}>click me</button>
        </div>
    );
}
}

render(<App />, document.getElementById("root"));

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.