1.1.1 • Published 4 years ago

@jonahgroup-hvpa/redux-obtain v1.1.1

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

Redux Obtain

redux-obtain works with React Redux to coordinate getting data from a server using React component lifecycles to manage the asychronous actions and Redux to store all of its state.

Build Status codecov npm npm version code style: prettier

Installation

npm install --save redux-obtain

or if you prefer yarn

yarn add redux-obtain

Usage

First, hook up redux-obtain into your root reducer:

import { createStore, combineReducers } from "redux"
import { reducer as resourceReducer } from "redux-obtain"

const rootReducer = combineReducers({
    // ...your other reducers here
    resources: resourceReducer
})

const store = createStore(rootReducer)

Then use a fetcher component to obtain some data

import React from "react"
import { fetcher } from "redux-obtain"

const TodoList = ({ data: { todos }, loading, error }) =>
    loading ? (
        <div>Loading</div>
    ) : error ? (
        <div>Error</div>
    ) : (
        <ul>{todos && todos.map((item, index) => <li key={index}>{item.text}</li>)}</ul>
    )

export default fetcher({
    name: "TODO_LIST",
    endpoint: "/todos",
    method: "GET"
})(TodoList)

It's as simple as that! redux-obtain will manage fetching/storing/removing all the data from your redux store for you.

Fetcher Options

OptionRequiredTypeDefaultPurpose
nameYESStringThis is the unique name given to the resource. It is required to access it
endpointYESString or SelectorThe endpoint to call for the resource. A redux store selector can be used for a dynamic endpoint.
methodYEShttp methodMethod to call endpoint
paginationKeyNOStringundefinedIf given, this enables pagination. The presence of this option overrides method, setting it to POST.
requestBodySelectorNOSelector() => undefinedSelects the request body from the redux store. Will trigger a Request for data if the result of the selector changes.
persistResourceNOBooleanfalseIf given, the resource will not remove itself from the store on unmount.
defaultOrderBysNOObject{ sortBy: [], sortDirection: [] }Used for paginated resources. This is the ordering that will be sent with the first request.
acceptResponseNOSelectorx => xThis is applied to the response from the server, before it is saved to the redux store. Normalization / Transformation should be done here.

Documentation

License

MIT