Skip to content

Instantly share code, notes, and snippets.

@choyan
Forked from tannerlinsley/createCrudHooks.js
Created August 20, 2021 23:56
Show Gist options
  • Select an option

  • Save choyan/9d51ee1a02dd220c5d6103a778616f58 to your computer and use it in GitHub Desktop.

Select an option

Save choyan/9d51ee1a02dd220c5d6103a778616f58 to your computer and use it in GitHub Desktop.

Revisions

  1. @tannerlinsley tannerlinsley created this gist Nov 29, 2020.
    37 changes: 37 additions & 0 deletions createCrudHooks.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,37 @@
    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]
    }
    16 changes: 16 additions & 0 deletions example.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,16 @@
    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}`),
    })