Reputation: 173
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
Upvotes: 0
Views: 331
Reputation: 62
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.
Upvotes: 0
Reputation: 18839
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).
Upvotes: 3