Dispatch an action based on the page the user is at

Viewed 32
const handleChangeCurrency = currency => {
/*if(user on currencyList component page) dispatch below twos*/
        dispatch({
            type: 'currencyList/emptyCurrencyList',
            payload: []
        })
        dispatch({
            type: 'currencyList/setCurrencyListConvertedState',
            payload: true
        })
/*if(user on currency component page) dispatch below twos*/
        dispatch({
            type: 'globalStats/setGlobalStatsConvertedState',
            payload: true
        })
        dispatch({
            type: 'currency/setCurrencyConvertedState',
            payload: true
        })
    }

Here, I have two components CurrencyList and Currency(specific) both of which render on different routes. But, I have a CurrencyChanger component which is universal i.e., is present on the whole application irrespective of route. Now, I want to dispatch some actions depending upon the page user is at. I don't wanna dispatch all the four actions everytime as it makes the application slow. Is there anything I can put inside if else block to dispatch them conditionally.

1 Answers

As discussed in the comments, one simple way is to use useLocation():

const location = useLocation();

const handleChangeCurrency = currency => {
    if(location.pathname === "/currency"){
        dispatch({
            type: 'currencyList/emptyCurrencyList',
            payload: []
        })
        dispatch({
            type: 'currencyList/setCurrencyListConvertedState',
            payload: true
        })
    } else if(location.pathname === "/currencyList"){
        dispatch({
            type: 'globalStats/setGlobalStatsConvertedState',
            payload: true
        })
        dispatch({
            type: 'currency/setCurrencyConvertedState',
            payload: true
        })
    }
}
Related