Skip to content

Instantly share code, notes, and snippets.

@tannerlinsley
Created November 29, 2020 06:39
Show Gist options
  • Star 87 You must be signed in to star a gist
  • Fork 9 You must be signed in to fork a gist
  • Save tannerlinsley/c6c0064239e0bcf40ca3703f95c0fb11 to your computer and use it in GitHub Desktop.
Save tannerlinsley/c6c0064239e0bcf40ca3703f95c0fb11 to your computer and use it in GitHub Desktop.
A naive, but efficient starter to generate crud hooks for React Query
export default function createCrudHooks({
baseKey,
indexFn,
singleFn,
createFn,
updateFn,
deleteFn,
}) {
const useIndex = (config) => useQuery([baseKey], indexFn, config)
const useSingle = (id, config) =>
useQuery([baseKey, id], () => singleFn(id), config)
const useCreate = (config = {}) =>
useMutation(createFn, {
...config,
onSuccess: (...args) => {
queryCache.invalidateQueries([baseKey])
if (config.onSuccess) config.onSuccess(...args)
},
})
const useUpdate = (config = {}) =>
useMutation(updateFn, {
...config,
onSuccess: (...args) => {
queryCache.invalidateQueries([baseKey])
if (config.onSuccess) config.onSuccess(...args)
},
})
const useDelete = (config = {}) =>
useMutation(deleteFn, {
...config,
onSuccess: (...args) => {
queryCache.invalidateQueries([baseKey])
if (config.onSuccess) config.onSuccess(...args)
},
})
return [useIndex, useSingle, useCreate, useUpdate, useDelete]
}
import createCrudHooks from './createCrudHooks'
const [
useTodos,
useTodo,
useCreateTodo,
useUpdateTodo,
useDeleteTodo,
] = createCrudHooks({
baseKey: 'todos',
indexFn: () => axios.get('/todos'),
singleFn: (id) => axios.get(`/todos/${id}`),
createFn: (payload) => axios.post(`/todos`, payload),
updateFn: (payload) => axios.patch(`/todos/${payload.id}`, payload),
deleteFn: (id) => axios.delet(`/todos/${id}`),
})
@jellekuipers
Copy link

thank you very much!
there is a small typo in the axios.delete deleteFn: (id) => axios.delet

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment