Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set state in child after it will receive props?

I have two components. One is UserBase on which ajax request is called to get values. When get those values and updated in state of header.

Another component is Header. Its a child component of UserBase. So when the state updated then it pass it to child component.

Now, my problem is I have to update the state of child when it will receive the props from the UserBase component. How can I achieve this functionality.

Here is my code

Header Component

var React = require('react');
var Router = require('react-router');
import Auth from './Auth.js';
import PopupSmall from './PopupSmall.js';

var headerStyle = {
    border:0
}

class Header extends React.Component{

    constructor(){
        super();
        console.log("constructor");
        this.state = {basicInfo : {}};
    }

    // **some function which needs to tigger when this component will receive props**

    popupChange(){
        console.log("============popupChange============");
        console.log(this.state);
        Router.browserHistory.push("/dashboard");
    }

    render(){
        if(this.props.basicInfo){

            return (
                <div>
                {this.props.basicInfo.isAgency==1 ? <PopupSmall popupCallBack={this.popupChange.bind(this)} itemList={this.props.agencies} show='true' title='Agencies'/> : console.log()}
            </div>
            )
        }

    }
}

export default Header;

UserBase Component

import React from 'react';
import Header from './Header.js';
import Auth from './Auth.js';
import Loader from './Loader.js';

var Router = require('react-router');

class Base extends React.Component{
    constructor(){
        super();
        this.state = {basicInfo :[]};
    }

    loadDataFromServer() {
        var tokenId = Auth.getCookies("token");

        if(tokenId!=""){

            var data = {
                token : tokenId
            }

            $.ajax({
              url: 'http://xxx.xxxxxxx.xxx/abc/cde',
              dataType: 'json',
              cache: false,
              type : 'POST',
              data : JSON.stringify(data),
              headers: { 
                    'Accept': 'application/json',
                    'Content-Type': 'application/json' 
                },
              success: function(response) {

                var info = {
                    compName : response.name,
                    firstName : response.fn,
                    isAgency : response.isAgeny
                }

                this.setState({basicInfo:info}, function(){
                    //console.log(this.state.data);
                }.bind(this));

              }.bind(this),
              error: function(xhr, status, err) {
                console.error("", status, err.toString());
              }.bind(this)
            });
        } else {
            Router.browserHistory.push('/login');
        }
    }

    componentDidMount() {
        this.loadDataFromServer();
    }

    render(){
        document.body.className="nav-md";

        return (

            <div className="container body">
              <div className="main_container">
                    <Header basicInfo={this.state.basicInfo} />
              </div>
            </div>

        );
    }
}

export default Base;
like image 761
Kushal Jain Avatar asked Jul 22 '16 07:07

Kushal Jain


People also ask

Can I setState in child component?

We can set Parent State from Children Component in ReactJs using the following approach. We will actually set the state of a parent in the parent component itself, but the children will be responsible for setting. We will create a function in parent to set the state with the given input.

What will happen when you use setState () in componentWillMount ()?

In Action. If we look at the gist below, this. setState() is used to change the name in componentWillMount() and componentDidMount() and the final name is reflected on the screen. An important thing to note here isthat as stated before, componentDidMount() occurs only once to give a render a second pass.

Can props change state?

To update state when props change in React:Pass the props as dependencies to the useEffect hook. Every time the props change, the logic in useEffect is reran.

Does child component Rerender when props change?

This doesn't only mean the component's render function will be called, but also that all its subsequent child components will re-render, regardless of whether their props have changed or not.


1 Answers

If you haven't already, have a read through: https://facebook.github.io/react/docs/component-specs.html

There's one function in particular which may suit what you need here:

componentWillReceiveProps(nextProps, nextState)

Invoked when a component is receiving new props. This method is not called for the initial render.

Use this as an opportunity to react to a prop transition before render() is called by updating the state using this.setState(). The old props can be accessed via this.props. Calling this.setState() within this function will not trigger an additional render.

So your Header component will have a function similar to the following in it (untested):

componentWillReceiveProps(nextProps) {
  if (nextProps.basicInfo !== this.props.basicInfo) {
    this.setState({ basicInfo: nextProps.basicInfo });
  }
}
like image 144
mnsr Avatar answered Oct 26 '22 12:10

mnsr