-
-
Save lukebrandonfarrell/d0d410042ca02c841f782685fcee6c2d to your computer and use it in GitHub Desktop.
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); | |
} | |
this is great, thanks!
@closetothe we have now extracted this into a module: https://github.com/aspect-apps/use-redux-effect
What's the purpose of comparing previous and current value? Ran into a bug where it wasnt updating subsequent messages of the same type because of this. Is this some sort of optimization?
@closetothe this is an outdated implementation, the problem with this is that if you fire two actions of the same type in sequence, the second action does NOT run an effect. Check out our latest implementation which solves this problem: https://github.com/aspect-apps/use-redux-effect/blob/master/src/use-redux-effect.ts
@closetothe this is an outdated implementation, the problem with this is that if you fire two actions of the same type in sequence, the second action does NOT run an effect. Check out our latest implementation which solves this problem: https://github.com/aspect-apps/use-redux-effect/blob/master/src/use-redux-effect.
I hate pulling lodash just for a single function but it's not too difficult to modify. Thanks for the link @lukebrandonfarrell
@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
That's pretty good.