connected-react-router icon indicating copy to clipboard operation
connected-react-router copied to clipboard

How to get current location in action creators

Open stevenWang0917 opened this issue 5 years ago • 1 comments

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?

stevenWang0917 avatar Oct 17 '20 04:10 stevenWang0917

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) } } }

DanielBailey-web avatar Jan 28 '21 17:01 DanielBailey-web