0.0.1-alpha.7 • Published 5 years ago

redux-crud-provider v0.0.1-alpha.7

Weekly downloads
4
License
MIT
Repository
github
Last release
5 years ago

Build Status

redux-crud-provider

This library is designed to store entities in redux and handles CRUD operations with a backend. It relies on redux-crud for handling redux and adds specific actions to create, read, update and delete entities on a backend.

How to

Define your entities

First, you need to define the entities used in your application.

The type of a ResourceDefinition can be found here.

Examples of ResourceDefinition can be found here.

Setup reducers

The library provides you with two reducers in order to keep track of the different entities of your application and the network activity.

createReducersForResources(entityDefinitions)
createActivityReducersForResources(entityDefinitions)

See an example of the redux setup here.

Selecting the entities from redux

To access the entities in your application, the library provides you with two selectors.

select(myResourceDefinition).asArray
select(myResourceDefinition).byId

Those can be used in your mapStateToProps like this:

import {select} from 'redux-crud-provider'

const mapStateToProps = state => ({
  books: select(BookResource).asArray(state),
  authorsById: select(AuthorResource).byId(state),
})

Setup the CRUD thunks

This library relies on redux-thunk in order to dispatch actions that will trigger backend calls. Make sure you have redux-thunk configured as a redux middleware in your application.

In order to update the entities in redux through backend calls, you need to create thunks.

const crudThunks = createCrudThunks(config)

The config needs to have this type. See an example here.

The createCrudThunks function will return an object with the following action creators:

Fetch all

crudThunks.fetchAll({resource, path, replace = false, params})

Parameters

NameTypeRequiredDescription
resourceResourceDefinitionyesThe resource that will be fetched
pathstringAn optional path to use to fetch the resources. resource.defaultPath is used by default
replacebooleanIf true, all entities in redux will be dropped and replaced with the result from the backend. If false, entities retrieved will be merged with the existing one.
paramsobjectAn optional object containing query params for the call

Fetch one

crudThunks.fetchOne({resource, path, uuid, params})

Parameters

NameTypeRequiredDescription
resourceResourceDefinitionyesThe resource that will be fetched
pathstringAn optional path to use to fetch the resource. ${resource.defaultPath}/${uuid} is used by default
uuidstringyesThe uuid of the entity that needs to be fetched
paramsobjectAn optional object containing query params for the call

Create

crudThunks.createResource({resource, path, entity})

Parameters

NameTypeRequiredDescription
resourceResourceDefinitionyesThe resource that will be created
pathstringAn optional path to use to fetch the resource. ${resource.defaultPath} is used by default
entityobjectyesAn object containing the properties that will be sent to the backend

Update

crudThunks.updateResource({resource, path, merge = true, entity, method, body})

Parameters

NameTypeRequiredDescription
resourceResourceDefinitionyesThe resource that will be updated
pathstringAn optional path to use to fetch the resource. ${resource.defaultPath}/${entity[resource.key]} is used by default
mergebooleanWhether or not to merge the entity provided with the existing entity in redux for the optimistic update
entityobjectyesAn object containing the properties that will be sent to the backend
methodstringThe method to use for the request. PATCH by default
bodyobjectSometimes you are calling a route that will return an updated entity but where the body you send is not such an entity. This is typically the case for custom actions. If you provide a body, it will be used instead of the entity for the request. The response will then be handled like normal and the entity in the store will be updated with the response.

Delete

crudThunks.deleteResource({resource, path, entity})

Parameters

NameTypeRequiredDescription
resourceResourceDefinitionyesThe resource that will be deleted
pathstringAn optional path to use to fetch the resource. ${resource.defaultPath}/${entity[resource.key]} is used by default
entityobjectyesAn object containing the properties that will be sent to the backend

Providers

Often, you won't need to use the thunks directly. Instead, the library provides you with react components that dispatch those actions for you.

ResourceListProvider

Example:

<ResourceListProvider crudThunks={crudThunks} resource={BookResource}>
  {({entities}) => (
    <ul>
      {entities.map(book => (
        <li key={book.id}>{book.name}</li>
      ))}
    </ul>
  )}
</ResourceListProvider>

Props

NameTypeRequiredDescription
childrenfunctionyesRender prop, see description below
resourceResourceDefinitionyesThe resource to use
pathstringPassed to crudThunks.fetchAll
replacebooleanPassed to crudThunks.fetchAll
paramsobjectPassed to crudThunks.fetchAll
autoFetchbooleanTriggers a call do the backend automatically to refresh the data in redux
loadingRenderReact ElementA react element to render while data are being fetched
crudThunksobjectyesThe result of createCrudThunks

Children function

The children function will be called with an object with the following properties:

NameTypeDescription
entitiesarrayThe list of entities
fetchAllfunctionA function to trigger a fetch from the backend
loadingbooleantrue when there is an ongoing call to the backend

ResourceProvider

Example:

<ResourceProvider
  crudThunks={crudThunks}
  resource={Book}
  uuid={match.params.uuid}
>
  {({entity}) => <h1>{entity.name}</h1>}
</ResourceProvider>

Props

NameTypeRequiredDescription
childrenfunctionyesRender prop, see description below
resourceResourceDefinitionyesThe resource to use
uuidstringyesThe uuid of the entity to manage
pathstringPassed to crudThunks.fetchOne, crudThunks.updateResource and crudThunks.deleteResource
paramsobjectPassed to crudThunks.fetchOne
autoFetchbooleanTriggers a call do the backend automatically to refresh the data in redux
loadingRenderReact ElementA react element to render while data are being fetched
crudThunksobjectyesThe result of createCrudThunks
postActionfunctionA function called after a successful update or delete

Children function

The children function will be called with an object with the following properties:

NameTypeDescription
entityanyThe entity
fetchEntityfunctionA function to re-fetch the entity from the backend
updateEntityfunctionA function to update the entity (calls the backend)
deleteEntityfunctionA function to delete the entity (calls the backend)
thunks.fetchOnefunctionThe fetchOne thunk already bound to dispatch
thunks.updateResourcefunctionThe updateResource thunk already bound to dispatch
thunks.deleteResourcefunctionThe deleteResource thunk already bound to dispatch
isFetchingbooleanTrue when the entity is being fetched
isUpdatingbooleanTrue when the entity is being updated
isRemovingbooleanTrue when the entity is being deleted

Peer dependencies

  • axios
  • react
  • react-redux
  • redux
  • reselect

yarn add axios react redux react-redux reselect