Send dispatch and redirect after state is updated in redux ?

511 Views Asked by At

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

2

There are 2 best solutions below

0
On

Eventually, I found workaround of my problem.

Really, my problem was in clearing state during browser reload. And when I try to use push(/) it reload webpage so state variable 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:

 <button className='btn btn-success' onClick={addTask}>Save</button>

to Link with to attribute that manual redirect:

<Link className='btn btn-success' to=`/` onClick={addTask}>Сохранить</Link>

onClick handle click (save new task) and to redirect to '/' url.

Thank you all for answers.

1
On

You should to know how treat async (like chain reaction) in react and redux.

Redux-saga helps you. https://github.com/redux-saga/redux-saga