redux-json-api
Version:
A bunch of Redux actions, action creators and reducers to integrate with a JSON API
86 lines (59 loc) • 2.28 kB
Markdown
Selectors
---
_redux-json-api_ provides a set of simple selectors.
Returns the state tree for the given resource type.
Returns the data (i.e. array of resources) for a given resource type
#### `getResource( state, resourceIdentifier: JsonApiResourceIdentifier ): JsonApiResource`
#### `getResource( state, resourceType: string, resourceId: string ): JsonApiResource`
Returns a specific resource based on the identifier, if that resource exists in the store.
##### Example
```jsx
import React from 'react';
import { useSelector } from 'react-redux';
import { getResource } from 'redux-json-api';
// Where taskId is the ID for a specific task.
const Task = ({ taskId }) => {
const task = useSelector((state) => getResource(state, 'tasks', taskId));
return <li>{task.title}</li>
};
export default Task;
```
Returns an array of resources based on the given identifiers.
```jsx
import React from 'react';
import { useSelector } from 'react-redux';
import { getResources } from 'redux-json-api';
// Where taskIds is an array of ids
const Tasks = ({ taskIds }) => {
const tasks = useSelector((state) => getResources(state, 'tasks', taskIds));
return <ul>
{tasks.map(task => (
<li>{task.title}</li>
))}
</ul>
};
export default Tasks;
```
Returns the related resources for the given resource.
```jsx
import React from 'react';
import { useSelector } from 'react-redux';
import { getRelatedResources } from 'redux-json-api';
// Where user is a JsonApiResource with a "tasks" relationship
const Tasks = ({ user }) => {
const tasks = useSelector((state) => getRelatedResources(state, user, 'tasks'));
return <ul>
{tasks.map(task => (
<li>{task.title}</li>
))}
</ul>
};
export default Tasks;
```