App.js
import "./App.css";
import { QueryClient, QueryClientProvider } from "react-query";
import Setting from "./components/Setting.js";
import Profile from "./components/Profile";
const queryClient = new QueryClient();
function App() {
return (
<QueryClientProvider client={queryClient}>
<div className="App">
<Setting />
<Profile />
</div>
</QueryClientProvider>
);
}
export default App;
exam_one/Setting.js
import { useState } from "react";
import { useQueryClient } from "react-query";
function Setting() {
const [username, setUsername] = useState("");
const queryClient = useQueryClient();
const handleClick = () => queryClient.setQueriesData("username", username);
return (
<div>
<input value={username} onChange={(e) => setUsername(e.target.value)} />
<button onClick={handleClick}>update</button>
</div>
);
}
export default Setting;
exam_one/Profile.js
import { useQuery } from "react-query";
function Profile(){
const {data: username} = useQuery('username', { initialData: '', staleTime: Infinity});
return <h1>{username}</h1>
}
export default Profile;
실행 화면
커스텀 훅 사용(재사용성 증가)
exam_one/Hooks.js
import { useQuery, useQueryClient } from "react-query";
export const useSetClientState = (key) => {
const queryClient = useQueryClient();
return (state) => queryClient.setQueryData(key, state);
};
export const useClientValue = (key, initialData) =>
useQuery(key, {
initialData,
staleTime: Infinity,
}).data;
exam_two/Async
import { QueryClient, QueryClientProvider, useQuery } from "react-query";
function Async() {
const { isLoading, error, data } = useQuery("repoData", () =>
fetch("https://api.github.com/repos/tannerlinsley/react-query").then(
(res) => res.json()
)
);
if (isLoading) return "Loading";
if (error) return "An error has occured: " + error.message;
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>
);
}
export default Async;
실행 화면