React Query Practice Exercises: Essential Techniques for Mastering the Framework

Here’s a short practice for using React Query:

Practice: Fetch Data using useQuery

  1. Create a new React app using create-react-app.
  2. Install React Query using yarn add react-query or npm install react-query.
  3. In your App.js file, import useQuery from react-query.
  4. 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, the useQuery hook fetches data from the JSON Placeholder API and returns the result to the component. The data, error, and isLoading variables are used to render the component based on the state of the query.
  5. Run your app and make sure the data is being fetched and rendered correctly.

Practice: Update Data using useMutation

  1. Expand on your previous app to allow users to create new todos.
  2. In your component, import useMutation from react-query.
  3. 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, the useMutation hook sends data to the JSON Placeholder API to create a new todo and updates the cache with the new data. The mutate function is called when the form is submitted, passing in the new todo data as an object.
  4. Run your app and make sure you can create new todos and see them rendered in the list of todos.
Tags: No tags

Add a Comment

Your email address will not be published. Required fields are marked *