Kramer
Kramer

Reputation: 399

Updating state from another component in Reactjs

I want to update the state of a main component from the "A" component then push it to "B" component and then use it render to dynamically populate boxes.

Main Component :

constructor() {
        super();
        this.state = {
            events:[],
            alerts:[],
        };

      }
  addEvent = newEvent => this.setState(state => {
    const {events} = this.state
    return [...events, newEvent]
  });

  addAlert = newAlert => this.setState(state =>{
    const {alerts} = this.state
    return [...alerts, newAlert]
  });

render(){
    const {events} = this.state
    const {alerts} = this.state
    console.log(events) // events are empty even after I pass and store it 
                        //   in SearchFlight Component  
    return(
        <div >

                <SearchFlight events={events} alerts={alerts} addAlert={this.addAlert} addEvent={this.addEvent} />
                <Events events={events}/>
                <Alerts />
            </div>

    );

}

SearchFlight Component(A component) :

handleSubmit= event =>{
        const {addEvent} = this.props
        const {addAlert} = this.props
        event.preventDefault();

        var newEvents=[];
        var newAlerts=[];


                 var singleEvent={
                   event_name:'home',
                   date_time:'12-08-18 12:45 AM',
                 };

                  newEvents.push(singleEvent);

                  newAlerts.push("Remove the luggage tag");

           addAlert(newAlerts);  
           addEvent(newEvents);

    }

Then I have Event Component(B Component) which right now just have render method. I want to get the updated events here.

Problem : Getting empty events when I did console.log(events) in render method of Main Component

Upvotes: 1

Views: 829

Answers (3)

Arshanwer
Arshanwer

Reputation: 1

As pointed out by OneJeet React is all about top-down approach and the child component should not be aware if a parent component is stateless or stateful.

Passing the setState as a function and allowing the child component to call it, is bad practice. One way is to use redux and eliminate the need to update parent state from child component or re-structure the whole thing in a different way.

Upvotes: 0

Shubham Khatri
Shubham Khatri

Reputation: 282000

You aren't using the setState correctly in addEvents and addAlerts method. the callback pattern of setState needs to return an object

addEvent = newEvent => this.setState(state => {
    const {events} = state
    return { events: [...events, ...newEvent]}
  });

  addAlert = newAlert => this.setState(state =>{
    const {alerts} = state
    return {alerts: [...alerts, ...newAlert]
  });

Also since events is an array of objects your need to iterate on them to render. Refer How to render an array of objects in React? answer for more details on how to do that

Upvotes: 1

onejeet
onejeet

Reputation: 1191

The State is private to the component. If the state is passed to the child component using props, again props should not be mutated as per the reactjs guidelines.

You can only read the value in Component A from the props and modify that value to pass it further to the nested components. But can't modify the state of the Main Component from A.

Check this out: https://reactjs.org/docs/state-and-lifecycle.html

Upvotes: 1

Related Questions