Hi I am working on a project ,in this project I am using Redux saga
for asynchronous action.I have a question when I dispatch an action to edit the user details, if the user Details successfully gets updated ,I want to redirect user to another page. This is working in my project but it's reloading the page ,I want it should not reload the page as I am using window.location
to redirect ,how can I use here react-router
to stop reloading,or is there any other way to do this
function* fetchData(){
try{
yield call(editgetUser)
yield put(userEditSuccess);
Window.location="/user/home"
} catch(e){
yield yield put(userEditFailure);
Window.location="/user/login"
}
}
function* watchFetchData(){
yield takeEvery(EDIT, fetchData);
}
I have been stucked in this kind of problem before, since you want to avoid page reload it means we have to use the history object provided by react-router-dom. We need the history object to achieve your goal but the history object is not available on the saga where the decision to navigate or not is taken, we have to find a way to pass the history object to the saga so that we can navigate from the saga. lets look at how we will achieve that
Solution 1 (Using react hook component)
Let say you are using react hook component thus the solution ..
// component to dispatch action
import {useHistory,useDispatch} from 'react-router-dom'
function MainComponent(){
const history = useHistory();
const dispatch = useDispatch();
return(
<div>
<button
onPress={()=>
dispatch({
type:"EDIT",
payload:{},
history:history // here we pass reference of history object
})}>Click ME </button>
</div>
)
}
// Your saga function modified
// add action as a param to fetchdata
function* fetchData(action){ // we take the action param
try{
yield call(editgetUser)
yield put(userEditSuccess);
Window.location="/user/home" // remove this line
action.history.push('/user/home') // add this line to your code
} catch(e){
yield yield put(userEditFailure);
Window.location="/user/login" // remove this line
action.history.push('/user/login') // add this line to your code
}
}
function* watchFetchData(){
yield takeEvery(EDIT, fetchData);// fetch data will have an action attatched to it as a param when called
}
if you are using a class component you can get history by calling this.props.history and pass the reference to the dispatched action.