Skip to content

Instantly share code, notes, and snippets.

@lukebrandonfarrell
Last active March 4, 2023 12:57
Show Gist options
  • Save lukebrandonfarrell/d0d410042ca02c841f782685fcee6c2d to your computer and use it in GitHub Desktop.
Save lukebrandonfarrell/d0d410042ca02c841f782685fcee6c2d to your computer and use it in GitHub Desktop.
A hook to listen to Redux actions in your component.
const initialState = {
type: null,
payload: null,
meta: null,
error: false
};
export default (state = initialState, action) => {
return {
...state,
...action
};
};
useReduxAction({ payload, error } => {
// Do something here
}, MY_REDUX_ACTION, []);
const reducers = combineReducers({
...
action: ActionReducer
});
/*
* 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);
}
@lukebrandonfarrell
Copy link
Author

@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