BuidlGuidl / grants.buidlguidl.com

https://grants-bg.vercel.app
MIT License
3 stars 3 forks source link

use swr for fetching and mutations #24

Closed technophile-04 closed 8 months ago

technophile-04 commented 8 months ago

Description

We could completely close this if it seems overpowered for the use case 🙌

Demo video of admin action :

https://github.com/BuidlGuidl/grants.buidlguidl.com/assets/80153681/ae960780-f0e1-492e-9ccd-e08f7733d7af

Notes :

Notes #### For fetching data `GET` request : 1. We just need to pass the API endpoint to `useSWR` hook and this also acts as a `key` 2. The `useSWR` will make the GET request with fetch and returns response data along with isLoading, `isError` etc 3. Whever an component mounts it will make the request (we can disbale it by `revalidateOnMount: false` ) eg : ```ts const { data, isLoading } = useSWR<{ data: GrantData[] }>("/api/grants/review"); ``` #### For `POST` : 1. 1st arg Pass the api endpoint 2. 2nd arg postMutationFetcher utility, (we could also pass body type to as generic) 3. call the trigger function by passing it the body ```ts const { trigger: postReviewGrant, isMutating: isPostingNewGrant } = useSWRMutation( `/api/grants/${grant.id}/review`, postMutationFetcher, ); // In some async function we can call trigger to make `POST` request : await postReviewGrant({ signer: address, signature, action }); await mutate("/api/grants/review"); // mutate comes from : const { mutate } = useSWRConfig(); ``` What this `mutate` function from `useSWRConfig` does is it internally makes the `GET` request for `url`/ `key` and updates its store maintained for that `key` / `url` Also notice in demo video although we made `GET` request to `/api/grants/review` api endpoint after posting review, it didn't show loading spinner and automatically removed the item. __I think__ they achieved this by "mutating" the store for that `key` / `url` properly. Lol I really this experience

Overall I love the experience and makes life a bit simple(like not creating useEffects, isLoading etc), but 100% agree it might be a bit overpowered

closes #22

vercel[bot] commented 8 months ago

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
grants-bg ✅ Ready (Inspect) Visit Preview 💬 Add feedback Feb 20, 2024 11:21am
carletex commented 8 months ago

Thank you very much for this <3 Top level stuff ;)

We could completely close this if it seems overpowered for the use case 🙌

Maybe.... but It's a great excuse to use swr (never used that lib before).... and we can learn it for future builds.