23
loading...
This website collects cookies to deliver better user experience
React Query is often described as the missing data-fetching library for React,
but in more technical terms, it makes fetching, caching, synchronizing and updating
server state in your React applications a breeze.
yarn add react-query
npm install react-query
import {
QueryClient,
QueryClientProvider,
} from "react-query";
const queryClient = new QueryClient();
ReactDOM.render(
<React.StrictMode>
<QueryClientProvider client={queryClient}>
<App />
</QueryClientProvider>
</React.StrictMode>,
document.getElementById('root')
);
const [data,setData] = useState([]); //state to hold our fetched data
useEffect(()=>{
fetchTodos();
})
const fetchTodos = async () => {
const todos = await getTodos(); //getTodos is an asynchronous function I created that fetches the todos for us and returns a promise
setData(todos); // setting the data in the state
}
return (
<div className="App">
<header>
<h1>Todos</h1>
</header>
<AddTodo />
{data.map((todo) => (
<Todo key={todo.id} text={todo.text} isDone={todo.is_done} id={todo.id} /> //component that presents the todos will get into it later
))}
</div>
);
import { useQuery } from "react-query";
import Todo from "./components/Todo";
import AddTodo from "./components/AddTodo";
import { getTodos } from "./apis";
function App() {
const { isLoading, isError, data, error } = useQuery("todos", getTodos); // a hook provided by react-query, it takes a key(name) and function that returns a promise
if (isLoading)
return (
<div className="App">
<h1>isLoading...</h1>
</div>
);
if (isError)
return (
<div className="App">
<h1>{error}</h1>
</div>
);
return (
<div className="App">
<header>
<h1>Todos</h1>
</header>
<AddTodo />
{data.map((todo) => (
<Todo key={todo.id} text={todo.text} isDone={todo.is_done} id={todo.id} />
))}
</div>
);
}
export default App;
import { useState } from "react";
import { useMutation, useQueryClient } from "react-query";
import { addTodo } from "../apis";
export default function AddTodo() {
const [todo, setTodo] = useState("");
const queryClient = useQueryClient();
const mutation = useMutation(addTodo, {
onSuccess: () => {
// Invalidate and refetch
setTodo("")
queryClient.invalidateQueries("todos");
},
});
return (
<div>
<input
value={todo}
onChange={(event) => {
setTodo(event.target.value);
}}
type="text"
/>
<button
onClick={() => {
mutation.mutate(todo);
}}
>
Add
</button>
</div>
);
}