Last active
February 13, 2025 07:09
-
-
Save lukebrandonfarrell/d0d410042ca02c841f782685fcee6c2d to your computer and use it in GitHub Desktop.
A hook to listen to Redux actions in your component.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const initialState = { | |
type: null, | |
payload: null, | |
meta: null, | |
error: false | |
}; | |
export default (state = initialState, action) => { | |
return { | |
...state, | |
...action | |
}; | |
}; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
useReduxAction({ payload, error } => { | |
// Do something here | |
}, MY_REDUX_ACTION, []); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const reducers = combineReducers({ | |
... | |
action: ActionReducer | |
}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* It's important to also use a action reducer | |
* which keeps track of the latest action for | |
* this to work. | |
*/ | |
import { useRef, useEffect } from "react"; | |
import { useStore } from "react-redux"; | |
import _castArray from "lodash.castarray"; | |
/** | |
* Subscribes to redux store events | |
* | |
* @param effect | |
* @param type | |
* @param deps | |
*/ | |
export function useReduxAction(effect, type, deps = []) { | |
const currentValue = useRef(null); | |
const store = useStore(); | |
const handleChange = () => { | |
const state = store.getState(); | |
const action = state.action; | |
let previousValue = currentValue.current; | |
currentValue.current = action.type; | |
if ( | |
previousValue !== action.type && | |
_castArray(type).includes(action.type) | |
) { | |
effect(action); | |
} | |
}; | |
useEffect(() => { | |
const unsubscribe = store.subscribe(handleChange); | |
return () => unsubscribe(); | |
}, deps); | |
} | |
@FullStackForger, maybe you could make a PR? (I agree)
This is a piece of gold, thanks
@PilotLeon checkout the package: https://github.com/aspect-apps/use-redux-effect
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I hate pulling lodash just for a single function but it's not too difficult to modify. Thanks for the link @lukebrandonfarrell