Here’s a short practice for using React Query:
Practice: Fetch Data using useQuery
- Create a new React app using
create-react-app
. - Install React Query using
yarn add react-query
ornpm install react-query
. - In your
App.js
file, importuseQuery
fromreact-query
. - Use the
useQuery
hook to fetch data from a public API. For example, you could fetch data from the JSON Placeholder API using the following code:javascriptCopy codeimport { useQuery } from 'react-query'; function App() { const { data, error, isLoading } = useQuery('todos', () => fetch('https://jsonplaceholder.typicode.com/todos').then((res) => res.json()) ); if (isLoading) { return <div>Loading...</div>; } if (error) { return <div>Error: {error.message}</div>; } return ( <div> {data.map((todo) => ( <div key={todo.id}>{todo.title}</div> ))} </div> ); }
In this example, theuseQuery
hook fetches data from the JSON Placeholder API and returns the result to the component. Thedata
,error
, andisLoading
variables are used to render the component based on the state of the query. - Run your app and make sure the data is being fetched and rendered correctly.
Practice: Update Data using useMutation
- Expand on your previous app to allow users to create new todos.
- In your component, import
useMutation
fromreact-query
. - Use the
useMutation
hook to send data to the JSON Placeholder API and update the cache with the new data. For example, you could use the following code to create a new todo:javascriptCopy codeimport { useMutation } from 'react-query'; function App() { const [mutate, { data, error, isLoading }] = useMutation((todo) => fetch('https://jsonplaceholder.typicode.com/todos', { method: 'POST', body: JSON.stringify(todo), headers: { 'Content-type': 'application/json; charset=UTF-8', }, }).then((res) => res.json()) ); const handleSubmit = (event) => { event.preventDefault(); const newTodo = { title: event.target.title.value }; mutate(newTodo); }; return ( <div> <form onSubmit={handleSubmit}> <input name="title" placeholder="New Todo" /> <button type="submit">Add</button> </form> {isLoading && <div>Creating todo...</div>} {error && <div>Error: {error.message}</div>} {data && <div>Todo created: {data.title}</div>} </div> ); }
In this example, theuseMutation
hook sends data to the JSON Placeholder API to create a new todo and updates the cache with the new data. Themutate
function is called when the form is submitted, passing in the new todo data as an object. - Run your app and make sure you can create new todos and see them rendered in the list of todos.