Introduction
The previous two exercises did not use any external API. This is actually not a common scenario in the real world.
When using APIs we need to manage our application's state and synchronize it with the API server. This is a challenging task and requires a lot of boilerplate code.
For this reason, it's better to use a library that allows us to manage the state of our application and synchronize it with the API. Examples of this are RTK Query and React Query. The former is a library that is part of the Redux Toolkit, and the latter is a standalone library.
Exercise 3 - To-Do List with RTK Query
We will now introduce an API that will be used to persist the tasks.
Using the RTK Query library, implement the following:
- Implement a form that allows the user to create a new task and persist it in the API.
- Implement a list that shows all the tasks and fetches them from the API.
- Implement a checkbox allowing the user to mark a task as completed and persist in the API.
- Implement a button that allows the user to delete a task and persist it in the API.
Use the dummyjson
TODOs API to fetch and persist the tasks.
You can check docs for the API here.
Use invalidation of data to update the list of tasks after a task is created, updated, or deleted. Alternatively, you can update the list of tasks in the API handlers for the mutations.
Alternative
If you want to avoid using Redux
and RTK Query
, you can use React Query
instead. This great library allows us to fetch data from an API and manage the state of the data.
This is actually the preferred way to manage API calls at eagerworks since it works very well with other libraries we will see in the future.
It is almost a global state management library, but its focus is synchronizing the state with the server.