yarn add swr
yarn add axios @types/axios
または
npm i swr -S
import useSWR from 'swr'
fetchを使用する場合 の fetcher の定義方法
const fetcher = (url) => fetch( url )
.then(res => res.json());
axiosを使用する場合 の fetcher の定義方法**
const fetcher = (url: string) => axios(url)
.then((res) => {
return res.data
});
function NewsIndex() {
const { data, error } = useSWR('https://YOUR/SERVER/PATH/api/news/', fetcher)
// swrによるfetchエラー時
if (error) return <div>failed to load</div>
// swrによるfetchロード中
if (!data) return <div>now loading...</div>
return (
<ul>
{data.map((v) =>
<li key={v.id}>{v.id} : {v.name}</li>
)}
</ul>
);
}
<div>
<NewsIndex/>
</div>
これで URL「https://YOUR/SERVER/PATH/api/news/」が返す json (中身はコレクション)の id と name を一覧で表示します。
デフォルトでは自動的に revalidate(再読込)処理が入っています。
「ページがフォーカスした時」 「タブを切り替えた時」 「設定したポーリング間隔」で再読み込みされます。
100msecとフォーカス時に自動再読込
const options = {
revalidateOnFocus,
refreshInterval: 100,
};
const { data, error, mutate } = useSWR(url, fetcher, options);
revalidateIfStale = true: automatic revalidation on mount even if there is stale data (details)
revalidateOnMount: enable or disable automatic revalidation when component is mounted
revalidateOnFocus = true: automatically revalidate when window gets focused (details)
revalidateOnReconnect = true: automatically revalidate when the browser regains a network
公式 : https://swr.vercel.app/docs/options
参考 : https://bit.ly/3Aicc4w
axios
const options = {
url: 'http://localhost/test.htm',
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json;charset=UTF-8'
},
data: {
a: 10,
b: 20
}
};
axios(options)
.then(response => {
console.log(response.status);
});
fetch
const url = 'http://localhost/test.htm';
const options = {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json;charset=UTF-8'
},
body: JSON.stringify({
a: 10,
b: 20
})
};
fetch(url, options)
.then(response => {
console.log(response.status);
});