connected-react-router
connected-react-router copied to clipboard
How to get current location in action creators
I got stuck with:
export const asyncGetImage = (url) => dispatch => { const fetchImage = async() => { try { const data = await fetch(url) const { code, status, ...apiData } = await data.json() if(code > 400){ dispatch(replace("/dogs/husky", { errorStatusCode: code })) } else { dispatch(getImage(apiData)) } } catch(err){ console.log(err) } } fetchImage() }
I want to use the current pathname (instead of "/dogs/husky") when dispatch replace. How to do that?
You can access the redux store in actions by providing a second function paramater nominally named getState which is a Function. To then get the state you would do something like:
const {state:{router}} = getState();
const location = router.location;
for a async function like you are doing, you would be trying to get the pathname variable out of the router
export const asyncGetImage = (url) => (dispatch,getState) => {
const fetchImage = async() => {
try {
const {state:{router}} = getState();
const {pathname, search} = router.location;
} catch(err){
console.error(err)
}
}
}