Recoilからjotaiに移行してしばらく経ったのでメモとして残しておきます。
基本的な使用方法
// 元となるatomの宣言。このままexportはしないほうがいい?
const counterState = atom(0);
// get専用のatom
export const getCounterState = atom((get) => {
return get(counterState);
});
// 使う時
cosnt counter = useAtomValue(getCounterState);
// set専用のatom
export const incrementAtom = atom(null, (get, set) => {
const current = get(counterState);
set(counterState, current + 1);
});
// 使う時
const increment = useSetAtom(incrementAtom);
// getとset両方を使うatom
export const counterAtom = atom(
(get) => {
return get(counterState);
},
(_, set, newValue: number) => {
set(counterState, newValue);
}
);
// 使う時
const [counter, setCounter] = useAtom(counterAtom);
SWRとの連携、urlのStateをjotaiに持たせる
const swrFetcher = async (url: string) => {
return axois.get(url).then((response) => {
return response.data;
});
};
//
export const urlAtom = atom((get) => {
// 元となるurl
const baseUrl = get(baseUrl);
const parameter = get(parameterAtom);
const newUrl = `${baseUrl}?parameter=${parameter}`
return newUrl;
});
const useFetch = () => {
const url = useAtomValue(urlAtom);
useEffect(() => {
mutate("fecthUrl");
}, [url]);
const { isLoading, error } = useSWR(
"fecthUrl",
() => {
return swrFetcher(url);
},
{
onSuccess: (data) => {
console.log(data)
},
}
);
return {
data,
isLoading,
error
};
};
このように書けば、parameter
の値が変更された時、parameterAtom
に依存しているurlAtom
が自動で再計算され、mutate()
が発火することによりSWRの再検証が行われる、という流れが実現できる。
このような処理はRecoilではselectorを用いるのが普通?だったが、jotaiにはそのような機能がない(selectAtomという機能はあるが基本的には非推奨)のでこのような形で処理を書く。
まだまだ使いこなせてない感があるので、また新しい知見が得られれば記事として残します。