Skip to content

Instantly share code, notes, and snippets.

@armouti
Last active April 25, 2022 11:48
Show Gist options
  • Save armouti/cf9bee2a83e427c18b69e484aa644ea0 to your computer and use it in GitHub Desktop.
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
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;
}
@armouti
Copy link
Author

armouti commented Apr 25, 2022

JS version

import { useEffect, DependencyList } from "react";
import { useDispatch, useSelector } from "react-redux";
import { Action } from 'redux';

/**
 * @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(
    action, 
    selector
) {
    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