Created
September 5, 2024 00:26
-
-
Save gseok/2721ba085906efe69f4bdd378d077d97 to your computer and use it in GitHub Desktop.
심플한 jotai debug 로직
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 { | |
myAtom1, | |
myAtom2, | |
myAtom3 | |
} from '@states/your.atoms'; | |
import { Atom, atom, useAtomValue, useStore } from 'jotai'; | |
import { useEffect } from 'react'; | |
type DictType<T = unknown> = Record<string, T>; | |
const logger = console; | |
const debugAtoms = { | |
myAtom1, | |
myAtom2, | |
myAtom3, | |
// eslint-disable-next-line @typescript-eslint/no-explicit-any | |
} as DictType<Atom<any>>; | |
const atoms = atom((get) => { | |
return Object.keys(debugAtoms).reduce((prev, debugAtom) => { | |
return { ...prev, [`${debugAtom}`]: get(debugAtoms[`${debugAtom}`]) }; | |
}, {}); | |
}); | |
export const DebugAtoms = () => { | |
const store = useStore(); | |
const allAtoms = useAtomValue(atoms); | |
if (typeof window !== 'undefined') { | |
window.jotai = allAtoms; | |
} | |
useEffect(() => { | |
if (!store) return; | |
const unsubs = [] as (() => void)[]; | |
Object.keys(debugAtoms).forEach((debugAtom) => { | |
unsubs.push( | |
store.sub(debugAtoms[`${debugAtom}`], () => { | |
logger.debug(`[Jotai] changed >`, { [`${debugAtom}`]: store.get(debugAtoms[`${debugAtom}`]) }); | |
}), | |
); | |
}); | |
return () => { | |
for (let i = 0; i < unsubs.length; i += 1) { | |
unsubs[i]?.(); | |
} | |
}; | |
}, [store]); | |
return null; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
최상위에서 개발환경일때만 로드해서 사용하는 형태로, 활용