1

From the title itself. I am fairly new to react and would like to know how would you update the already "passed" data from parent to child. I have an alert component that will display the error message depending on the data acquired after an Axios request.

Parent ..

    this.state = { 
                formContact: { 
                    fullname: '',
                    contact:'',
                    email: '',
                    message: ''
                },
                formAlert: { alertMessage: 'default'}
            };

     handleClick() {

            let rm = this;
            axios({
                method: 'post',
                url: 'submit',
                data: {
                    form: this.state.formContact
                    }
                })
                .then(function (response) {
                    let data = response.data.data;
                    rm.setState({ 
                        formAlert: { alertMessage: 'test' }
                    });

                }).catch(function (response) {
                    //handle error
                    console.log(response);
                });
        }

  render() {
        return (
            <div className="row">
               <Alert data={this.state.formAlert}  />
            </div>
       );
    }
}

Child

class Alert extends Component {
    constructor(props) {
        super(props);
        console.log(props);

        // Holds the form state and input boxes
        this.state = { 
            formError: { 
                icon: '',
                header: '',
                message: '',
                errorType: 'errormsg'
            }
        };
    }
    render() {
        return (
            <div className={'style-msg ' + this.state.formError.errorType}>
                <div className="sb-msg"><i className="icon-thumbs-up"></i>
                    <strong>Well done!</strong>
                    {this.state.formError.message}
                </div>
                <button type="button" className="close" data-dismiss="alert" aria-hidden="true">×</button>
            </div>
        );
    }
}

It seems I cannot update the formAlert.alertMessage to "test" and pass the new data "test" to the child.

Any help would greatly be appreciated. Thanks

2 Answers 2

2

As you have passed data to Alert component,

<Alert data={this.state.formAlert}  />

But in Alert component, you have never used that data.

I think instead of this,

{this.state.formError.message}

you should use this,

{this.props.data.alertMessage}

Update

In order to set props to state do this,

formError: { 
   icon: '',
   header: '',
   message: props.data.alertMessage,
   errorType: 'errormsg'
}

Now you can use,

{this.state.formError.message}

When data changes after first render your Alert component's state will not get new data, for this you need componentDidUpdate method,

componentDidUpdate(prevProps, prevState) {
  if (prevProps.data.alertMessage !== this.props.data.alertMessage) {
    let formError = {...this.state.formError};
    formError.message = this.props.data.alertMessage
    this.setState({formError},()=>console.log(this.state.formError.message))
  }
}
5
  • Yes it works. However, I want the props.data.alertMessage to be set on t he Child's this.state.formError. message and then render the updated object @ravibagul91
    – drake24
    Aug 7, 2019 at 12:19
  • Tried it. But the state.formError.message is still using the same value and not from the axios result that I was hoping for. @ravibagul91
    – drake24
    Aug 7, 2019 at 12:29
  • it's better to use the props when the parent data is updated after that component rerender again and no need to use state Aug 7, 2019 at 12:46
  • 1
    @ravibagul91 Thank you it really worked. But i also somehow manage to have my solution. Just a question though I used this this.alert = React.createRef(); and created a function inside Alert.js named update(data) in which data stores the newly updated data being accepted inside the axios. Is my solution also correct? or using the componentDidUpdate the proper way? Thank you
    – drake24
    Aug 8, 2019 at 4:46
  • 1
    Yes. ref can be used to trigger function from child component, but only for class based component and not for functional component. Aug 8, 2019 at 4:58
0

Your Child Component should use the data props to show the alert.

    class Alert extends Component {
    constructor(props) {
        super(props);
        console.log(props);

        // Holds the form state and input boxes
        this.state = { 
            formError: { 
                icon: '',
                header: '',
                message: '',
                errorType: 'errormsg'
            }
        };
    }
    render() {
        return (
            <div className={'style-msg ' + this.state.formError.errorType}>
                <div className="sb-msg"><i className="icon-thumbs-up"></i>
                    <strong>Well done!</strong>
                    {this.props.data.alertMessage}
                </div>
                <button type="button" className="close" data-dismiss="alert" aria-hidden="true">×</button>
            </div>
        );
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.