Skip to content

Instantly share code, notes, and snippets.

@cglacet
Created July 26, 2022 09:30
Show Gist options
  • Save cglacet/eca5194a99e1d47f7cc7ee8c8350f148 to your computer and use it in GitHub Desktop.
Save cglacet/eca5194a99e1d47f7cc7ee8c8350f148 to your computer and use it in GitHub Desktop.
import {
QueryClient,
QueryClientProvider,
useQuery
} from "@tanstack/react-query";
import * as yup from "yup";
const TEST_ERROR = false;
const queryClient = new QueryClient();
const userValidator = yup.object({
id: yup.string().required(),
name: yup.string().required(),
email: yup.string().email().nullable().notRequired()
});
// You could do this too:
// type UserType = yup.InferType<typeof userValidator>
async function testFetch(url: string) {
const userId = url.split("/").slice(-1)[0];
return {
json: async () => ({
id: userId,
name: TEST_ERROR ? 42 : "Christian"
})
};
}
function UserData(userId: string) {
return useQuery(["user-query"], async () => {
const res = await testFetch(`api/user/${userId}`);
const data = await res.json();
return userValidator.validate(data, { strict: true });
});
}
function User({ userId }: { userId: string }) {
const { data, isLoading } = UserData(userId);
if (isLoading) {
return <h1>Loading</h1>;
}
if (!data) {
return <h1>Who are you?</h1>;
}
return <h1>Hello {data.name}</h1>;
}
export default function App() {
return (
<div className="App">
<QueryClientProvider client={queryClient}>
<User userId="test-user-id" />
</QueryClientProvider>
</div>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment