-
Notifications
You must be signed in to change notification settings - Fork 1.2k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
feat(types): clarify SWRResponse type #2175
base: main
Are you sure you want to change the base?
Conversation
@sanding0 do you know why wasnt this merged? it would be great!! Or is there a workaround? |
@tobbbe I think so too. Isn't this change better than now? Why you(@sanding0) closed? I expected SWRResponse will work like union Response type like @tanstack/react-query but it isn't. I'm so sad about this SWRResponse's data as undefined.🥲 |
@shuding @huozhi Then, Do we need to use useSWR like below to type narrowing? const SWRComp = () => {
const swrQuery = useSWR(...)
if(swrQuery.data !== undefined){
return <>{swrQuery.data}</>
}
} but in this case, if fetcher to put in useSWR return undefined, how can we do guarantee fetcher's returning promise is success? I'm sad that there is no isSuccess flag in useSWR because of this problem. @shuding @huozhi, Could you make it TypeScript example to guide us avoiding this problem? In this example(https://swr.vercel.app/examples/basic) in official guide in JavaScript file. I can understand it because of JavaScript will accept it. but in TypeScript is not!🥲 In JavaScript, no type errorimport React from "react";
import useSWR from "swr";
const fetcher = (url) => fetch(url).then((res) => res.json());
export default function App() {
const { data, error, isLoading } = useSWR(
"https://api.github.com/repos/vercel/swr",
fetcher
);
if (error) return "An error has occurred.";
if (isLoading) return "Loading...";
return (
<div>
<h1>{data.name}</h1>
<p>{data.description}</p>
<strong>👁 {data.subscribers_count}</strong>{" "}
<strong>✨ {data.stargazers_count}</strong>{" "}
<strong>🍴 {data.forks_count}</strong>
</div>
);
} In TypeScript, Type error will be occuredimport React from 'react'
import useSWR from 'swr'
const fetcher = (
url: string
) => fetch(url).then((res) => res.json()) as Promise<{
name: string
description: string
subscribers_count: number
stargazers_count: number
forks_count: number
}>
export default function App() {
const { data, error, isLoading } = useSWR(
'https://api.github.com/repos/vercel/swr',
fetcher
)
if (error) return 'An error has occurred.'
if (isLoading) return 'Loading...'
return (
<div>
<h1>{data.name}</h1>
<p>{data.description}</p>
<strong>👁 {data.subscribers_count}</strong>{' '}
<strong>✨ {data.stargazers_count}</strong>{' '}
<strong>🍴 {data.forks_count}</strong>
</div>
)
} How do we have to avoid this type error situation? |
I dont think we need |
fix #2482
This PR can clarify
SWRResponse
typeallows you to asser response types in TypeScript