Last active
April 25, 2022 11:48
-
-
Save armouti/cf9bee2a83e427c18b69e484aa644ea0 to your computer and use it in GitHub Desktop.
A hook to help in migrating from Redux to SWR, use it before the return value inside the custom hooks that wrap useSWR to loop the value through redux
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
import { useEffect, DependencyList } from "react"; | |
import { useDispatch, useSelector } from "react-redux"; | |
import { Action } from 'redux'; | |
import { IGlobalState } from "../../../redux/GlobalState"; | |
type Selector<T> = (state: IGlobalState) => T; | |
/** | |
* @param action The redux action object, pass null or undefined to prevent dispatch | |
* @param selector A selector function, it should return the state targeted by the 'action' argument | |
* @param deps the dependency array to optimize for the invocation of this hook | |
* @returns Value from selector | |
*/ | |
export function useThroughRedux<T>( | |
action: Action | undefined | null, | |
selector: Selector<T>, deps: DependencyList | |
): T | undefined { | |
const dispatch = useDispatch(); | |
const value = useSelector(selector); | |
useEffect(() => { | |
if (action) { | |
dispatch(action); | |
} | |
}, deps); | |
return value; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
JS version