Resource Objects
Each resource slice has a property called resources
. All of your resource data is stored here. If your application manages books, then you may have the following resource slice:
The resources
object allows you to quickly access any resource given its ID. For instance, the following code demonstrates accessing the data for the book with ID 102:
Note: For more advanced retrieval of resources from the store, you can use the
getResources
method.
What is a Resource?
Resources are the individual pieces of data that come from your backend. For instance, if you're using a RESTful API, you might have an endpoint, GET /books/24
, that returns you the information for the book with the ID 24. That information is a single resource.
The only requirement of a resource is that it must have an id
property. The following are some examples of valid resources:
We understand that not all backend services return data that have an ID attribute. For such services, a transformation function will need to be written to change that data into Redux Resource-compatible resources. We understand that this isn't ideal, but we believe the benefits of Redux Resource outweigh this inconvenience.
Here are some examples of common data formats that a backend may send over, and how you can change them into Redux Resource compatible resources.
Modifying Resources
There are two ways to modify resources: synchronously and asynchronously. The guide on modifying resources describes both of these approaches.
Best Practices
A good rule of thumb is to treat the resource objects as the last-known source of truth from the server. In other words, don't modify the resource objects within the resources
section of a slice unless the server tells you that they have changed.
For local changes in your application, such as form data, you should store that information somewhere else. You can store it wherever you think is best: your favorite forms library, component state, or even in the metadata section of the resource slice.
A good workflow that implements this pattern is:
Fetch resources from the server
Place them into the
resources
section of a resource sliceIf the user can modify resources, store the user's modification information somewhere other than
in the
resources
section of the resource sliceOnce you persist those changes to the server, and the server responds, update
the
resources
with the latest information from the server
Following this pattern will help keep you organized, even as your application grows.
Last updated