😀
useMutationを使ったCRUD処理まとめ
get
import useSWRMutation from 'swr/mutation'
async function getRequest(url) {
return fetch(url, {
method: 'GET',
}).then(res => res.json())
}
function App() {
const { data, trigger, isMutating } = useSWRMutation('/api/todo', getRequest)
return (
<button
disabled={isMutating}
onClick={async () => {
try {
const result = await trigger()
} catch (e) {
// error handling
}
}}
>
Get Todo List
</button>
)
}
post
import useSWRMutation from 'swr/mutation'
interface Todo {
title: string,
isCompleted: boolean
}
async function postRequest(url, { arg }: { arg: Todo }) {
return fetch(url, {
method: 'POST',
body: JSON.stringify(arg)
}).then(res => res.json())
}
function App() {
const { data, trigger: createTodo, isMutating: isCreating } = useSWRMutation('/api/todo', postRequest)
return (
<button
disabled={isCreating}
onClick={async () => {
try {
const newTodo: Todo = {
title: 'New Todo',
isCompleted: false
}
const result = await createTodo(newTodo)
} catch (e) {
// error handling
}
}}
>
Create Todo
</button>
)
}
put
import useSWRMutation from 'swr/mutation'
interface Todo {
title: string;
isCompleted: boolean;
}
interface PutRequestArgs {
requestBody: Todo;
queryParams: {
id: string
};
};
async function putRequest(url, { arg }: { arg: PutRequestArgs }) {
return fetch(url + '?' + new URLSearchParams(arg.queryParams), {
method: 'PUT',
body: JSON.stringify(arg.requestBody)
}).then(res => res.json())
}
function App() {
const { data, trigger: updateTodo, isMutating: isUpdating } = useSWRMutation('/api/todo', putRequest)
return (
<button
disabled={isUpdating}
onClick={async () => {
try {
const newTodo: Todo = {
title: 'New Todo',
isCompleted: false
}
const result = await updateTodo({
requestBody: newTodo,
queryParams: { id: 'todoIDToBeUpdated' }
})
} catch (e) {
// error handling
}
}}
>
Update Todo
</button>
)
}
delete
未完成
onSuccessを使う方法では以下のようなものがあった
Discussion