Unable to correctly update parent object state

Asked
Active3 hr before
Viewed126 times

9 Answers

objectparentcorrectlyunablestateupdate
90%

Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers ,This way the child can update the parent's state with the call of a function passed with props., Meta Stack Overflow

For child-parent communication you should pass a function setting the state from parent to child, like this

class Parent extends React.Component {
  constructor(props) {
    super(props)

    this.handler = this.handler.bind(this)
  }

  handler() {
    this.setState({
      someVar: 'some value'
    })
  }

  render() {
    return <Child handler = {this.handler} />
  }
}

class Child extends React.Component {
  render() {
    return <Button onClick = {this.props.handler}/ >
  }
}

load more v
88%

In this tutorial, we've seen how to access and update the state of a parent component from a child component.,You can send the state of the parent component as a prop to the child component:,ContactForm is a child component of App.

class ContactForm extends React.Component {


    state = {
        name: '',
        email: '',
        country: '',
        city: '',
        job: '',

    }



    handleFormSubmit( event ) {
        event.preventDefault();


        let formData = new FormData();
        formData.append('name', this.state.name)
        formData.append('email', this.state.email)
        formData.append('city', this.state.city)
        formData.append('country', this.state.country)
        formData.append('job', this.state.job)

        axios({
            method: 'post',
            url: '/api/contacts.php',
            data: formData,
            config: { headers: {'Content-Type': 'multipart/form-data' }}
        })
        .then(function (response) {
            //handle success
            console.log(response)

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

    render(){
        return (
        <form>
            <label>Name</label>
            <input type="text" name="name" value={this.state.name}
                onChange={e => this.setState({ name: e.target.value })}/>

            <label>Email</label>
            <input type="email" name="email" value={this.state.email}
                onChange={e => this.setState({ email: e.target.value })}/>

            <label>Country</label>
            <input type="text" name="country" value={this.state.country}
                onChange={e => this.setState({ country: e.target.value })}/>

            <label>City</label>
            <input type="text" name="city" value={this.state.city}
                onChange={e => this.setState({ city: e.target.value })}/>

            <label>Job</label>
            <input type="text" name="job" value={this.state.job}
                onChange={e => this.setState({ job: e.target.value })}/>

            <input type="submit" onClick={e => this.handleFormSubmit(e)} value="Create Contact" />
        </form>);
    }
}
load more v
72%

ourcodeworld.com is using a security service for protection against online attacks. The service requires full cookie support in order to view this website. , ourcodeworld.com is using a security service for protection against online attacks. This process is automatic. You will be redirected once the validation is complete. , ourcodeworld.com is using a security service for protection against online attacks. The service requires full JavaScript support in order to view this website.

Pretag
 Pretag team - issue, fix, solve, resolve
65%

Hi, I have a problem when trying to update the parent state via child component in a functional component.,I tried this solution, but it only works on the first invocation in my child component.,have the child own the state - so that only it updates (not the whole parent)

class Parent extends React.Component {
  state = { value: "" }

  handleChange = (newValue) => {
    this.props.setState({ value: newValue });
  }
  
  render() {
    // We pass a callback to MyInput
    return <MyInput value={this.state.value} onChange={this.handleChange} />
  }
}

class MyInput extends React.Component {
   handleChange = (event) => {
    // Here, we invoke the callback with the new value
    this.props.onChange(event.target.value);
  }

  render() {
	return <input value={this.props.value} onChange={this.handleChange} />
  }
}
load more v
75%

Pretag
 Pretag team - issue, fix, solve, resolve
40%

How to update the state of a parent component from a child component is one of the most commonly asked React questions.,You're already prop drilling, or passing things from the parent RecipeBox component to its child EditList properly. But when someone enters text into the input box and clicks "Submit", the state isn't updated the way you expect.,Then update the recipe for the element you want to update. Let's do the first element as a proof of concept:

import React from "react";
import ReactDOM from "react-dom";

import RecipeBox from "./RecipeBox";

const rootElement = document.getElementById("root");
ReactDOM.render(
<React.StrictMode>
   <RecipeBox />
</React.StrictMode>,
rootElement
);
load more v
22%

On the above codes, we have created function handleChange that will pass the value through props.onChange to our Parent component.,As you see that we set the onChange property to the Child component. Next step is to create the Child component.,React hooks are introduced in React 16.8. If you are familiar with the class components then there is no difference to change the parent component state from child component.

Child component holds the Input field and we are going to send the input field value to the Parent component. So let’s create the Parent component first.

function Parent() {
    const [value, setValue] = React.useState("");

    function handleChange(newValue) {
      setValue(newValue);
    }

    // We pass a callback to Child
    return <Child value={value} onChange={handleChange} />;
}
load more v
60%

This also provides the flexibility to only reset parts of our component’s internal state if we so choose. (Click here to see a demo of this pattern.),Recommendation: To reset all internal state, use the key attribute.,Even though the example above shows componentWillReceiveProps, the same anti-pattern applies to getDerivedStateFromProps.

class EmailInput extends Component {
  state = { email: this.props.email };

  render() {
    return <input onChange={this.handleChange} value={this.state.email} />;
  }

  handleChange = event => {
    this.setState({ email: event.target.value });
  };

  componentWillReceiveProps(nextProps) {
    // This will erase any local state updates!
    // Do not do this.
    this.setState({ email: nextProps.email });
  }
}
load more v
48%

Pretag
 Pretag team - issue, fix, solve, resolve

Other "object-parent" queries related to "Unable to correctly update parent object state"