Let's say I have following action:
export function signIn(data) {
return {
type: USER_SIGN_IN,
promise: api.post('/sign_in', data)
}
}
and the following middleware:
export default function promiseMiddleware() {
return next => action => {
const { promise, type, ...rest } = action
if (!promise) {
return next(action)
}
const SUCCESS = `${type}_SUCCESS`
const REQUEST = `${type}_REQUEST`
const ERROR = `${type}_ERROR`
next({ ...rest, type: REQUEST })
return promise
.then(res => {
next({ ...rest, response: res.data, type: SUCCESS })
return true
})
.catch(error => {
next({ ...rest, response: error.response.data, type: ERROR })
return false
})
}
}
This code is loosely based on https://github.com/reactGo/reactGo/
But what if in then
callback after calling next
I want to make a redirect to another path?
I did following. I passed redirect url through action:
export function signIn(data) {
return {
type: USER_SIGN_IN,
promise: api.post('/sign_in', data),
redirect: '/'
}
}
and added another call of next
method with push
from react-router-redux
:
import { push } from 'react-router-redux'
export default function promiseMiddleware() {
return next => action => {
const { promise, type, redirect, ...rest } = action
if (!promise) {
return next(action)
}
const SUCCESS = `${type}_SUCCESS`
const REQUEST = `${type}_REQUEST`
const ERROR = `${type}_ERROR`
next({ ...rest, type: REQUEST })
return promise
.then(res => {
next({ ...rest, response: res.data, type: SUCCESS })
next(push(redirect))
return true
})
.catch(error => {
next({ ...rest, response: error.response.data, type: ERROR })
return false
})
}
}
It seems like it works, but I'm not sure if this is a good idea or if there are some pitfalls of multiple next
calls and I shouldn't do like this? Or maybe I should use dispatch
method which I can get from promiseMiddleware
params instead of next
for redirecting?
If there are some better approaches for implementing such redirects, please, let me know.