Closed aiwon0035 closed 8 months ago
jotaiのatomWithStorageを使うことで、usestateをlocalstrageと同期できる
しかしapp routerで使うと無限ループが起きる、、 https://github.com/pmndrs/jotai/discussions/1798
jotaiは使用するが、atomWithStorageは使用しないことにする
できた! ドキュメントにこう書かないと無限ループするって書いてあった https://stackoverflow.com/questions/73746466/why-jotai-makes-a-component-infinitely-re-render-when-i-define-the-related-atom https://jotai.org/docs/core/use-atom
けどメモ化したことで値をsetできなくなってしまった いや、AddTaskコンポではsetしたらすぐ反映されたのに、TaskListコンポではできなかった(おそらくコンポーネント内だけでしか値を保持できていない?)
const [derivedAtomValue] = useAtom( useMemo( // This is also fine () => atom((get) => get(stableAtom) * 2), [], ), )
このドキュメントのサンプルで、どのようにderivedAtomValueを更新したらいいのかわからなかった
export const useFormAtom = (id: string) => { const formAtom = useMemo(() => atomWithStorage(id, []), [id]);
const [formValue, setFormValue(これが存在しない、never型になる)] = useAtom<FormType[]>(formAtom);
return { formValue, setFormValue, formAtom }; };
こういう形でidを動的に変更しつつ値を保持するのは不可能だと判断(値は保持できるがリアルタイムで表示できない)
export const todosAtom = atomWithStorage("todos", {});
このように1つのキーで全てのtodoを保持することにした(レンダリング範囲が広くなりそうで本当は避けたかった)
export const Aampleaaa = ({ id }: { id: string }) => { const [value, setValue] = useState(1);
// 1. atomWithStorage を使ってローカルストレージと同期されるアトムを作成 const formAtom = useMemo( () => atom((get) => get(atomWithStorage(id, value))), [id, value] );
// 2. useAtom フックを使用してアトムの値を取得 const [derivedAtomValue] = useAtom(formAtom);
return ( <> {derivedAtomValue} {/ {value} /} <button onClick={() => setValue((c) => c + 1)}>+ </> ); };
これも無理だった const [,] =atomWithStorageの形にしなかんから?
これでいけた!
//カスタムフック const idFamily = atomFamily((id: string) => atomWithStorage<FormType[]>(id, []) );
export const useTodosAtom = (id: string) => { const [todos, setTodos] = useAtom(idFamily(id));
return { todos, setTodos }; };
const { todos, setTodos } = useTodosAtom(id);
jotaiを使う
atomの初期値に、idを指定して取得したlocalstrageの値を入れたい タスク追加時や編集時にlocalstrageとatomの値を同時に更新する
画面に表示させるのはlocalstrageの方?atomの方? →atomの方にしてみる