Sakib Mulla
Sakib Mulla

Reputation: 83

react not updating array state

if I clicked the button to update name then it's not changing using setState I want update persons variable and as well it should update in the DOM.

Please suggest me idea how to update the state

App.js

import React, { Component } from "react";
import Person from "./component/Person";
import "./App.css";

class App extends Component {
  constructor() {
    super();
    this.state = {
      persons: [
        { name: "max", age: 28 },
        { name: "manu", age: 29 },
        { name: "step", age: 26 }
      ]
    };
  }

  chnagenames = () => {
    console.log("clicked me ");
    this.setState = {
      persons: [
        { name: "maxi", age: 28 },
        { name: "manr", age: 29 },
        { name: "step", age: 27 }
      ]
    };
    console.log(this.state.persons);
  };

  render() {
    return <> {/* ... */} </>;
  }
}

export default App;

Person.js

import React from "react";

const Person = props => {
  return (
    <>
      person age is {props.ages} and name is {props.attrib}{" "}
    </>
  );
};

export default Person;

Upvotes: 0

Views: 67

Answers (2)

YangDi0027
YangDi0027

Reputation: 21

please try this :

chnagenames = () => {
    console.log("clicked me ");
    var changedArray = [
        { name: "maxi", age: 28 },
        { name: "manr", age: 29 },
        { name: "step", age: 27 }
      ];

    this.setState({
      persons: changedArray
    }, function {
      console.log(this.state.persons);});    
  };

Upvotes: 0

Tholle
Tholle

Reputation: 112777

You should call this.setState as it is a function, not assign a new value to it.

You also have a typo on the chnagenames method, and setState is also asynchronous so you will not see the change if you log it directly after setState.

changenames = () => {
  console.log("clicked me ");
  this.setState(
    {
      persons: [
        { name: "maxi", age: 28 },
        { name: "manr", age: 29 },
        { name: "step", age: 27 }
      ]
    },
    () => console.log(this.state.persons)
  );
};

Upvotes: 1

Related Questions