0

I have a React component which i need to update when i call onSubmit on a child component

The parent component which needs to get updated looks like this:

componentDidMount() {
    axios.get('/todo')
        .then(function (response) {
            this.setState({
                todoList: response.data
            })
        }.bind(this))
        .catch(function (error) {
            console.log(error);
        });
}

render() {
    return (
        <div>
            <Form/>
            {this.state.todoList.map(todo => {
                return (
                    <TodoItem
                        id={todo._id}
                        key={todo._id}
                        itemToDo={todo.todoItem}

                    />
                );
            })}
        </div>
    )
  }

When i submit the <Form/> component i call

handleSubmit(e) {
    e.preventDefault();
    axios.post('/todo', {
        todoItem: this.state.todoItem
    })
}

where i need to update the parent component, in order to get the updated list from the server

2 Answers 2

3

I am not sure entirely about your question but you can pass a function (updateParent) from parent component to the child component as a property and when you want to update the parent component, invoke this.props.propFromParentComponent in your child component. If you want the parent component to update, use the this.setState({..}) and update the state of the component to update the parent component inside of this function (updateParent).

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your answer. The only thing i have a state in my parent component is todoList. Can i just create something else to operate on purely to update the component?
I'm not the person you're responding to, but, yes. You should create a function that will be used simply to handle the update, and then, as AliF50 said, pass that function as a prop to the child component, who will then be able to invoke it.
0

If you have a store that the parent component is listening to for prop changes you could have the child component update the store which would in turn update the parent. This would be assuming you have a unidirectional flow of data.

If you need to have the child component directly update it's parent the answer AliF50 supplied would work.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.