Say I have the following component named Home:

this.state = {
    posts: []
componentDidMount() {
    ... data is fetched from api

    <PostForm />
    { => (
     <Post key={} post={post} />

How would I update the state of Home, or re fetch data from the api after the the PostForm component is submitted with a new Post.

Solution 1

Welcome to SO!

Setting the parent state from the child:

If you want your child component to have access to your parent component's state, just pass setState() as a prop in your parent class, like so...

    setParentState={(state) => this.setState(state)}

Then, later in PostForm.js, just set the parent state like so....


Or, you can even just do....


And later on, you can call anything in postform with this.props.postform.anyFunctionEver().

Setting the child state from the parent:

Suppose you want to do the opposite now: update the state of the child component from the parent? That's just as easy, set a reference when defining <PostForm/>...

    ref={(instance) => {this.postform = instance}}

Then you can set the postform's state directly in your parent class...


A lot can happen with the state, so if you're not sure, try making a testFunc() {console.log('test');}, and then try passing/activating this between parent and child.