useSWRの複数引数で詰まった

2023/06/29に公開

共通部分

const fetchWithToken = (url, token) => {
	const response = await fetch(url, {
	      method: 'GET',
	      headers: {
		'Content-Type': 'application/json',
		Authorization: `Bearer ${token}`,
	      },
	    });
	const res = await response.json();
	return res
}

❌ 間違った記述

const { data } = useSWR(['/api/threads', token], fetchWithToken)
const { data } = useSWR('/api/user', url => fetchWithToken(url, token))

✅ 正しい記述

const { data } = useSWR(['/api/threads', token], ([url, token]) => fetchWithToken(url, token)

参考

https://swr.vercel.app/ja/docs/arguments#multiple-arguments

Discussion