2

I'm trying to push a new component to an array that holds other equal components. My parent component is receiving that array from the server and renders it.

I logged this action and in the console, there is a new value but I don't see the new component on the screen.

Parent Component:

state = {
  meetingsArr: [
    {
      id: 1,
      metName: "driving lesson",
      metTime: "45 min",
      setTime: "10 min",
      metCost: "100",
      metInfo: "some text"
    }
  ]
};

addMeetting = () => {
  this.state.meetingsArr.push(<SingleMetting />);
  console.log(this.state.meetingsArr);
};

render() {
  const { meetingsArr } = this.state;
  return (
    <div>
      {meetingsArr.map(item => (
        <SingleMetting key={item.id} data={item} />
      ))}

      <div className="new-met">
        <button className="btn" onClick={this.addMeetting}>
          create a new metting
        </button>
      </div>
    </div>
  );
}

2 Answers 2

2

you should use setState(...) to modify the state:

addMeetting = () => {
    const newMeeting = {
        id: 2,
        metName: 'whatever',
        metTime: 'whatever',
        setTime: 'whatever',
        metCost: 'whatever',
        metInfo: 'some other text'
    }
    this.setState({meetingsArr: [...(this.state.meetingsArr ||[]), newMeeting]})
}
Sign up to request clarification or add additional context in comments.

Comments

0

Accessing the state inside the setState function is an anti pattern, because the fact that setState function/method is an async process. The “correct way” to update the state using the state 🤯 what ?? Well just use the callback function

state = {
 myArr: []
}
....
methodHandler () {
 this.setState(prevState => ({myArr: [...prevState.myArr,  {
        id: 2,
        metName: 'whatever',
        metTime: 'whatever',
        setTime: 'whatever',
        metCost: 'whatever',
        metInfo: 'some other text'
    }]});

2 Comments

Hey Ernesto, I understand what you're saying but this solution doesn't work :/
take a look to my exampre here: codepen.io/jaraolveda/project/editor/DaJYMY

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.