swr/mutation
useSWRMutation
hook
useSWR
, useSWRInfinite
에서는 데이터를 부른 후 mutate 와 revalidate를 진행useSWRMutatuon
혹에서는 trigger
라는 선언형 함수를 통해 API fetch할 수 있다before :
import useSWR from `swr`
const fetcher = async([url, params]) => {
return fetch(url, {
method: 'POST',
body: JSON.stringify(params)
})
}
const myApp = () => {
const [shouldFetch, setShouldFetch] = useState<boolean>(false)
const params = {
titile: 'some post',
content: 'this is some post'
}
const {
data,
isValidatig,
} = useSWR(() => shouldFetch ? [`/api/post`, params] : null, fetcher)
const fechHandler: MouseEventHandler<HTMLButtonElement> = (e) => {
e.preventDefault()
if(!data) {
setShouldFetch(true)
}
}
return (
<button
disabled={isValidatig}
onClick={() => setShouldFetch(true)}
>
)
}
shouldFetch (boolean)
조건을 통해 키를 추가 혹은 null
value로 넣을지 구분하여 conditional data fetching 처리after :
import useSWRMutation from 'swr/mutation'
const fetcher = async(url, { arg }) => {
return fetch(url, {
method: 'POST',
body: JSON.stringify(arg)
})
}
const myApp = () => {
const {
trigger,
isMutatiing,
data,
error,
reset
} = useSWRMutation(`/api/post`, fetcher)
return (
<button
disabled={isMutating}
onClick={() => trigger({ title: 'some post '})}
>
)
}