Included Resources
APIs frequently support returning multiple resource types in a single request. For instance, an endpoint may allow you to fetch an author as well as that author's books. In this example, authors and books are two different resource types.
This plugin is designed to allow you to dispatch a single action that includes multiple types. It is optimized to receive normalized data, such as what is returned from normalizr.

Usage

Add this plugin when you call resourceReducer. Be sure to add it to the "primary" resource slice, as well as to the included resource slices.
1
import { resourceReducer } from 'redux-resource';
2
import { includedResources } from 'redux-resource-plugins';
3
4
const authorReducer = resourceReducer('authors', {
5
plugins: [includedResources]
6
});
7
8
const booksReducer = resourceReducer('books', {
9
plugins: [includedResources]
10
});
Copied!
This plugin doesn't come with any custom action types. Instead, it changes the way the state is transformed with the built-in successful create, update or read CRUD action type: CREATE_RESOURCES_SUCCEEDED, UPDATE_RESOURCES_SUCCEEDED and READ_RESOURCES_SUCCEEDED.
When your actions have an includedResources object, they will be added to the appropriate slices.
An example of using includedResources is the following:
1
import { actionTypes } from 'redux-resource';
2
import store from './store';
3
4
store.dispatch({
5
type: actionTypes.READ_RESOURCES_SUCCEEDED,
6
resourceType: 'authors',
7
resources: [{
8
id: 10,
9
name: 'Sarah'
10
}],
11
includedResources: {
12
// Resources are key'd off by their name.
13
// The value can be an Object or an Array.
14
15
// Here we pass books as an Object. `normalizr` returns
16
// a shape like this.
17
books: {
18
23: {
19
id: 23,
20
name: 'Some book'
21
},
22
100: {
23
id: 50,
24
name: 'Another book'
25
}
26
},
27
28
// Notice here that comments is an Array. This format works, too.
29
comments: [
30
{
31
id: 23,
32
name: 'Great author!'
33
},
34
{
35
id: 100,
36
name: 'One of my favorite authors'
37
}
38
]
39
}
40
});
Copied!
Be sure to use includedResources on every resource slice that can appear in includedResources. In the above example, we would want to include the plugin for our authors, books, and comments.
This plugin will respect the mergeResources and mergeMeta action properties.

Related Reading

Not every API returns included resources in a normalized manner, so a different plugin may be more appropriate for certain backends. As an example, JSON API does not provide included resources in a format that can be interpreted by this plugin.
For more on this subject, refer to the Related Resources recipe.
Last modified 2yr ago
Copy link