Created
February 2, 2024 14:34
-
-
Save samuelint/0e15dcde1e288dc17f842265bb6d0edd to your computer and use it in GitHub Desktop.
This file contains 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 { ActionCreatorWithPayload } from '@reduxjs/toolkit'; | |
import { useEffect } from 'react'; | |
import { useDispatch, useSelector } from 'react-redux'; | |
interface Props< | |
TValue, | |
TAction extends ActionCreatorWithPayload<TValue>, | |
// eslint-disable-next-line @typescript-eslint/no-explicit-any | |
TSelector extends (state: any) => TValue | |
> { | |
initial: TValue | |
action: TAction | |
selector: TSelector | |
} | |
export default function useHydrate< | |
TValue, | |
TAction extends ActionCreatorWithPayload<TValue> = ActionCreatorWithPayload<TValue>, | |
// eslint-disable-next-line @typescript-eslint/no-explicit-any | |
TSelector extends (state: any) => TValue = () => TValue | |
>({ initial, action, selector }: Props<TValue, TAction, TSelector>) { | |
const dispatch = useDispatch(); | |
useEffect(() => { | |
dispatch((action(initial))); | |
// Call only once | |
// eslint-disable-next-line react-hooks/exhaustive-deps | |
}, []); | |
return useSelector(selector); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment