From e3627e30e802645a497b645292957afd506c7c4a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?H=C3=A5kon=20Underbakke?= Date: Fri, 29 Sep 2023 10:52:24 +0200 Subject: [PATCH] docs: added draft of SWR resolver --- docs/docs/Features/other-libs.md | 56 ++++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) diff --git a/docs/docs/Features/other-libs.md b/docs/docs/Features/other-libs.md index 9844e86..9d045b6 100644 --- a/docs/docs/Features/other-libs.md +++ b/docs/docs/Features/other-libs.md @@ -15,6 +15,7 @@ Although `rtk-query-loader` was build with `@reduxjs/toolkit` in mind, the under [See example on CodeSandbox](https://codesandbox.io/s/tanstack-query-rtk-query-loader-example-6393w2) ```typescript +import { useQueryResult } from "@ryfylke-react/rtk-query-loader"; import { useQuery, UseQueryResult as TanstackUseQueryResult, @@ -71,6 +72,61 @@ const loader = createLoader({ The output format will obviously be a bit different, but in this example you have access to the original query at the `.original_query` property. +## SWR + +```typescript +import { UseQueryResult } from "@ryfylke-react/rtk-query-loader"; +import useSWR, { SWRResponse, Key } from "swr"; + +const swrResolver = (res: SWRResponse): UseQueryResult => { + const q = { + data: res.data, + isError: res.error ? true : false, + isLoading: res.isLoading, + isFetching: res.isLoading && res.data !== undefined, + isSuccess: res.data ? (res.error ? false : true) : false, + startedTimeStamp: new Date().getTime(), + isUninitialized: !res.isLoading && !res.data, + refetch: () => { + res.mutate(); + }, + currentData: res.data, + endpointName: "unknown", + originalArgs: "unknown", + requestId: "unknown", + error: res.error, + fulfilledTimeStamp: new Date().getTime() + }; + console.log(q); + return q; +}; + +export const useSWRQuery = ( + key: TArgs, + fetcher: (args: TArgs) => Promise +) => { + return swrResolver(useSWR(key, fetcher)); +}; +``` + +This is how you would use it: + +```typescript +import { useTanstackQuery } from "../loader-resolvers"; + +const loader = createLoader({ + useQueries: (pokemonName?: string) => { + const pokemon = useSWRQuery(pokemonName ?? "charizard", getPokemon); + + return { + queries: { + pokemon, + }, + }; + }, +}); +``` + ## Other libraries If you are interested in creating resolvers for other libraries, you can [edit this page](https://github.com/ryfylke-react-as/rtk-query-loader/tree/main/docs/docs/Advanced/other-libs.md) and then [submit a pull request](https://github.com/ryfylke-react-as/rtk-query-loader/compare) on GitHub to share your resolver here, as an npm package, or with the code embedded directly in the docs.