Created
November 19, 2021 23:43
-
-
Save marcincodes/2cf91ed0f2705692fefce92da58ab01d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// hooks/useUser.js | |
export const getUser = async ({ id }) => { | |
const { data, error } = await db | |
.from('users') | |
.select('*') | |
.eq('id', id) | |
.single(); | |
if (error) { | |
throw new Error(error.message) | |
} | |
if (!data) { | |
throw new Error("User not found") | |
} | |
return data | |
} | |
export const useUser = (id) => { | |
return useQuery(['users', id], () => getUser({ id })); | |
}; | |
// pages/_app.js | |
const queryClient = new QueryClient({ | |
defaultOptions: { | |
queries: { | |
retry: 0 | |
} | |
} | |
}); | |
export default function MyApp({ Component, pageProps }) { | |
return ( | |
<QueryClientProvider client={queryClient}> | |
<Hydrate state={pageProps.queryData}> | |
<Layout> | |
<Component {...pageProps} /> | |
</Layout> | |
</Hydrate> | |
</QueryClientProvider> | |
); | |
} | |
// pages/user.js | |
export default function User({ id }) { | |
const { data: user } = useUser(id); | |
return ( | |
<section className="bg-black"> | |
{user.name} | |
</section> | |
); | |
} | |
export async function getServerSideProps(context) { | |
const queryClient = new QueryClient() | |
await queryClient.prefetchQuery(['users', context.params.id], () => getUser({ id: context.params.id })); | |
return { | |
props: { | |
queryData: dehydrate(queryClient), | |
id: context.params.id | |
}, | |
}; | |
} | |
// hooks/useUpdateUser.js | |
export const updateUser = async (id, values) => { | |
const { data, error } = await db | |
.from('users') | |
.update(values) | |
.eq('id', id); | |
if (error) { | |
throw new Error(error.message); | |
} | |
return data; | |
}; | |
export const useUpdateConfig = (id, args = {}) => { | |
const queryClient = useQueryClient(); | |
return useMutation((data) => updateConfig(id, data), { | |
...args, | |
onSuccess: (data) => { | |
queryClient.invalidateQueries(['users', id]); | |
if (typeof args.onSuccess === 'function') { | |
args.onSuccess(data); | |
} | |
} | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment