Skip to content

Instantly share code, notes, and snippets.

@gseok
Created September 5, 2024 00:26
Show Gist options
  • Save gseok/2721ba085906efe69f4bdd378d077d97 to your computer and use it in GitHub Desktop.
Save gseok/2721ba085906efe69f4bdd378d077d97 to your computer and use it in GitHub Desktop.
심플한 jotai debug 로직
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;
};
@gseok
Copy link
Author

gseok commented Sep 5, 2024

최상위에서 개발환경일때만 로드해서 사용하는 형태로, 활용

export const App = () => {
  return (
    <>
      <YourComponents />
      {isLocalDev && <JotaiAtomDebug />}
    </>
  );
};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment