I am new in front end development. Now I do study project (simple task editor, without server side) on base of reactJs+redux. I encounter with next problem.
I have some component that show web page on url '/addTask/'.
const TaskCreator = ({ tasks, onAddTask }) => {
...
const addTask = () => {
const newTask = {
id: newId,
header: headerInput.value,
description: descriptionInput.value
}
onAddTask(newTask);
}
return(
<div>
...
<button className='btn btn-success' onClick={addTask}>Save</button>
</div>
);
}
export default connect(
(state) => ({
tasks: state.tasks
}),
dispatch => ({
onAddTask: (task) => {
const payload = {
id: task.id,
header: task.header,
description: task.description
};
dispatch({ type: 'ADD_TASK', payload });
browserHistory.push('/');
}
})
)(TaskCreator);
When user click on button Save. addTask has called. After that onAddTask method faired and ADD_TASK task command disptached.
After new task has added to state there is need to redirect to url /.
When I insert statement browserHistory.push('/'), browser redirect to url / but it didn't update state with new task. If I delete statement browserHistory.push('/') like that
onAddTask: (task) => {
const payload = {
id: task.id,
header: task.header,
description: task.description
};
dispatch({ type: 'ADD_TASK', payload });
}
The state updated but browser didn't redirect.
How can I asynchronously update state (using dispatch) and after state has updated, redirect to url / ?
Thanks for advance
Eventually, I found workaround of my problem.
Really, my problem was in clearing
stateduring browser reload. And when I try to usepush(/)it reload webpage sostatevariable cleared and can't see new (added in '/addTask/' page) tasks on '/' url.To avoid clearing webpage there is need to go back (in browser) or manually print '/' url. I found programmatical analog for manual enter '/' url. To do this there is need to change:
to Link with
toattribute that manual redirect:onClickhandle click (save new task) andtoredirect to '/' url.Thank you all for answers.