Skip to content

Latest commit

 

History

History
456 lines (303 loc) · 12.7 KB

docs.md

File metadata and controls

456 lines (303 loc) · 12.7 KB

Table of Contents

handleSuccess

A function that takes an API action handler and only applies that handler when the request succeeds.

Parameters

  • handler Function An action handler that is passed state, action and data params

Examples

handleActions({
   [apiActions.fetchUser]: handleSuccess((state, action) => {
     // This code only runs when the call was successful
     return set('currentUser', action.payload.data, state)
   })
})

Returns Function An action handler that runs when a request is successful

handleFailure

A function that takes an API action handler and only applies that handler when the request fails.

Parameters

  • handler Function An action handler that is passed state, action and data params

Examples

handleActions({
   [apiActions.fetchUser]: handleFailure((state, action) => {
     // This code only runs when the call was unsuccessful
     return set('userFetchError', action.payload.data, state)
   })
})

Returns Function An action handler that runs when a request is unsuccessful

handleResponse

A function that takes two API action handlers, one for successful requests and one for failed requests, and applies the handlers when the responses have the correct status.

Parameters

  • successHandler Function An action handler that is passed state, action and data params
  • failureHandler Function An action handler that is passed state, action and data params

Examples

handleActions({
   [apiActions.fetchUser]: handleResponse(
     (state, action) => {
       // This code runs if the call is successful
       return set('currentUser', action.payload.data, state)
     },
     (state, action) => {
       // This code runs if the call is unsuccessful
       return set('userFetchError', action.payload.data, state)
     },
   )
})

Returns Function An action handler runs the handler that corresponds to the request status

setOnSuccess

A function that creates an API action handler that sets a path in the state with the returned data if a request succeeds.

Parameters

  • path String The path in the state to set with the returned data
  • transform Function? A function that determines the data that is set in the state. Passed action and state params.

Examples

handleActions({
   // This will do the same thing as the example for handleSuccess
   [apiActions.fetchUser]: setOnSuccess('currentSuccess')
})

Returns Function An action handler that runs when a request is unsuccessful

setOnFailure

A function that creates an API action handler that sets a path in the state with the returned error if a request fails.

Parameters

  • path String The path in the state to set with the returned error
  • transform Function? A function that determines the data that is set in the state. Passed action and state params.

Examples

handleActions({
   // This will do the same thing as the example for handleFailure
   [apiActions.fetchUser]: setOnFailure('userFetchError')
})

Returns Function An action handler that runs when a request is successful

setOnResponse

A function that creates an API action handler that sets one of two given paths in the state with the returned data depending on whether a request succeeds or fails.

Parameters

  • path String The path in the state to set with the returned data on success
  • path String The path in the state to set with the returned error on failure
  • transform Function? A function that determines the success data that is set in the state. Passed action and state params.
  • transform Function? A function that determines the error data that is set in the state. Passed action and state params.

Examples

handleActions({
   // This will do the same thing as the example for handleResponse
   [apiActions.fetchUser]: setOnResponse('currentUser', 'userFetchError')
})

Returns Function An action handler

LP_API

A unique key that identifies dispatched actions to be handled by the LP Redux Api middleware. This is implemented as a Symbol, instead of a String to guarantee uniqueness.

The params provided as the value include anything that is supported by LP Redux Api Middleware

Type: Symbol

Examples

// An example action creator
function fooAction () {
  return {
    [LP_API]: {
      url: 'http://foo.com/posts',
      requestAction: 'REQUEST',
      successAction: 'SUCCESS',
      failureAction: 'FAILURE',
    }
  }
}

createRequest

A function that creates action creators for making API requests, much like createAction from redux-actions.

Note: there are convenience functions for each request method: createPostRequest(), createPutRequest(), etc.

Parameters

  • type String A unique key that will be used to identify the request internally in redux
  • definition (Object | Function) An object of config options for the adapter, or a function that returns config options.

Examples

export const fetchUser = createRequest('FETCH_USER', (id) => ({
  url: '/users/' + id,
}))

fetchUsers(5)
// -> will make request to /users/5

// Just like in redux-actions, this action can be referenced in a reducer by name:

handleActions({
   [apiActions.fetchUser]: (state, action) => ...
})

Returns Function An action creator that passes its arguments to definition and makes the resulting API request.

middleware

In order to use actions created by createRequest, you must apply the custom lp-redux-api middleware to your store when the store is created:

import { middleware as apiMiddleware } from '@launchpadlab/lp-redux-api'

const defaultAdapterOptions = { ... }
const adapter = axios

const middleware = applyMiddleware(
   apiMiddleware(adapter, defaultAdapterOptions),
   ...
)
const store = createStore(reducer, initialState, middleware)

The adapter argument is the function that will be invoked to make the API request. It will be passed an object of configuration arguments and it must return a promise indicating request status.

The following options may be used to configure the middleware:

  • onUnauthorized (default=null): An action creator to be called and dispatched when the server rejects a request with a status of unauthorized.
  • requestAction (default=null): An action creator to be called and dispatched when the initial request is made.
  • successAction (default=null): An action creator to be called and dispatched if the request succeeds.
  • failureAction (default=null): An action creator to be called and dispatched if the request fails.
  • any options used by the adapter

reducer

Stores the status of API requests in your state. Statuses are stored for all requests with a requestKey (including those created by requestWithKey), and can be retrieved by using selectStatus.

To use this reducer, add it to combineReducers() under the api key. You can use a different key if you'd like, but you will need to reference it explicitly when using selectStatus.

Type: Function

Examples

// When creating store, attach reducer

import { reducer as apiReducer } from 'lp-redux-api'

combineReducers({ 
  api: apiReducer,
  ...
})

// Now you can keep track of request status elsewhere in your app

import { requestKey, selectStatus } from 'lp-redux-api'

const REQ_FETCH_USERS = 'REQ_FETCH_USERS'
dispatch(requestWithKey(REQ_FETCH_USERS, { url: '/users' }))

selectStatus(REQ_FETCH_USERS, state) // -> 'loading'

selectors

This library exports the following selectors for determining the status of requests:

  • selectors.status(state, requestAction, [slice])
  • selectors.hasStatus(state, requestAction, [slice])
  • selectors.isLoading(state, requestAction, [slice])
  • selectors.isComplete(state, requestAction, [slice])
  • selectors.isSuccess(state, requestAction, [slice])
  • selectors.isFailure(state, requestAction, [slice])

In order to work, the lp-redux-api reducer must be included in combineReducers(). Selectors expect the reducer to be keyed under 'api'- if a different key is used, it must be passed as the optional slice parameter.

The status returned by selectors.status() can be one of the following exported constants:

  • LP_API_STATUS_LOADING: 'loading'
  • LP_API_STATUS_SUCCESS: 'success'
  • LP_API_STATUS_FAILURE: 'failure'

Examples

// When creating store, attach reducer

import { reducer as apiReducer } from 'lp-redux-api'

combineReducers({ 
  api: apiReducer,
  ...
})

// Now you can keep track of request status elsewhere in your app

import { createRequest, selectors as apiSelectors } from 'lp-redux-api'

const fetchUsers = createRequest('FETCH_USERS', { url: '/users' })
dispatch(fetchUsers())

apiSelectors.status(state, fetchUsers) // -> 'loading'

createStubRequest

A function that creates action creators for making stubbed API requests.

Unlike createRequest, these action creators do not make real API calls but rather resolve immediately with the provided data.

If an exception is thrown from the data creator function, the "request" will reject with that exception instead of resolving.

Parameters

  • type String A unique key that will be used to identify the request internally in redux

  • dataDefinition (Object | Function) Data that the request will resolve with, or a function that returns data to resolve with.

  • options Object? Options object

    • options.delay Number Time (in ms) to delay the API request. Particularly useful when attempting to simulate loading states. (optional, default 0)

Examples

// ** Stubbing a successful request: **

export const fetchUser = createStubRequest('FETCH_USER', (id) => ({ id }))

fetchUsers(5)
// -> won't make any api request, but will resolve with data { id: 5 }

// Just like in redux-actions, this action can be referenced in a reducer by name:

handleActions({
   [apiActions.fetchUser]: (state, action) => ...
})

// ** Stubbing a failed request: **

export const fetchUser = createStubRequest('FETCH_USER', (id) => {
   throw new Error('My mock error.')
})

fetchUsers(5)
// -> won't make any api request, but will reject with the given error.

// ** Simulating a response delay: **

export const fetchUser = createStubRequest('FETCH_USER', (id) => {
 return {
   id
 }}, { delay: 500 })

Returns Function An action creator that passes its arguments to dataDefinition and makes the resulting stubbed API request.