Created
November 3, 2022 10:07
-
-
Save pei223/51817f484ea0935aa2421283f335ba25 to your computer and use it in GitHub Desktop.
SWR helper
This file contains 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
import ky from "ky"; | |
const baseApi = ky | |
.create({ | |
prefixUrl: "http://localhost:8080", | |
headers: { "Content-Type": "application/json" }, | |
}); | |
type TodoList = { | |
items: Todo[]; | |
total: number; | |
}; | |
type Todo = { | |
id: string; | |
title: string; | |
done: boolean; | |
}; | |
const fetcher = ( | |
url: string | |
): Promise<TodoList> => { | |
return baseApi | |
.get(url) | |
.json(); | |
}; | |
const useTodos = ( | |
options?: SWRConfiguration | |
) => { | |
const { data, error, mutate } = useSWR<TodoList>( | |
["todos", ], | |
fetcher, | |
options | |
); | |
return { | |
data, | |
loading: !error && !data, | |
error, | |
mutate, | |
}; | |
}; | |
const TodosPage = () => { | |
const { data, loading, prevData, mutate } = withPrevData( | |
useTodos({ page: 0, limit: 10 }, { refreshInterval: 5000 }) | |
); | |
// render using data/prevData | |
} |
This file contains 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
import { useEffect, useRef, useState } from "react"; | |
import { ApiHookResult } from "./types"; | |
import { KeyedMutator } from "swr"; | |
export type ApiHookResult<ResType> = { | |
data?: ResType; | |
loading: boolean; | |
error?: Error; | |
mutate: KeyedMutator<ResType>; | |
}; | |
/** | |
* Add prevData to ApiHookResult | |
* @param hookResult SWR hook result | |
* @returns hookResult with prevData | |
*/ | |
export const withPrevData = <T>( | |
hookResult: ApiHookResult<T> | |
): ApiHookResult<T> & { prevData: T | undefined } => { | |
const [prevData, setPrevData] = useState<T | undefined>(undefined); | |
const prevDataRef = useRef<T | undefined>(undefined); | |
useEffect(() => { | |
setPrevData(prevDataRef.current); | |
prevDataRef.current = hookResult.data; | |
}, [hookResult.data]); | |
return { ...hookResult, prevData }; | |
}; | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment