React and Redux: redirect after action

I am developing a site using React / Redux and I am using thunk middleware to call my API. My problem is redirection after actions.

I really don't know how and where I can do the redirection: in my action, in the gearbox, in my component, ...?

My actions are as follows:

export function deleteItem(id) { return { [CALL_API]: { endpoint: `item/${id}`, method: 'DELETE', types: [DELETE_ITEM_REQUEST, DELETE_ITEM_SUCCESS, DELETE_ITEM_FAILURE] }, id }; } 

react-redux already implemented on my website, and I know I can do this as shown below, but I don't want to redirect use if the request is not completed:

 router.push('/items'); 

Thanks!

+5
source share
3 answers

Typically, it is best practice to redirect in a component as follows:

 render(){ if(requestFullfilled){ router.push('/item') } else{ return( <MyComponent /> ) } } 
+5
source

Definitely do not redirect your gears, as they should be free from side effects. It looks like you are using api-redux-middleware, which, it seems to me, does not have a success / failure / completion callback, which I think will be a pretty useful feature for the library.

In this question from an intermediate repo, the repo owner offers something like this:

 // Assuming you are using react-router version < 4.0 import { browserHistory } from 'react-router'; export function deleteItem(id) { return { [CALL_API]: { endpoint: `item/${id}`, method: 'DELETE', types: [ DELETE_ITEM_REQUEST, { type: DELETE_ITEM_SUCCESS, payload: (action, state, res) => { return res.json().then(json => { browserHistory.push('/your-route'); return json; }); }, }, DELETE_ITEM_FAILURE ] }, id } }; 

I personally prefer having a flag in my connected components, which, if true, will direct to the page I need. I would set componentWillReceiveProps as follows:

 componentWillReceiveProps(nextProps) { if (nextProps.foo.isDeleted) { this.props.router.push('/your-route'); } } 
+12
source

In the Redux realm, you need to use action-redux-router push action instead of browserHistory.push

 import { push } from 'react-router-redux' store.dispatch(push('/your-route')) 
+1
source

Source: https://habr.com/ru/post/1265843/


All Articles