0

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;
1
  • 1
    It seems you could have a typo: chnagenames. Is clicked me logged in the console? Commented Mar 16, 2019 at 18:57

2 Answers 2

1

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)
  );
};
Sign up to request clarification or add additional context in comments.

1 Comment

@SakibMulla You're welcome! Consider accepting one of the answers if you feel any of them answered your question.
0

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);});    
  };

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.