- handleSuccess
- handleFailure
- handleResponse
- setOnSuccess
- setOnFailure
- setOnResponse
- LP_API
- createRequest
- middleware
- reducer
- selectors
- createStubRequest
A function that takes an API action handler and only applies that handler when the request succeeds.
handler
Function An action handler that is passedstate
,action
anddata
params
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
A function that takes an API action handler and only applies that handler when the request fails.
handler
Function An action handler that is passedstate
,action
anddata
params
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
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.
successHandler
Function An action handler that is passedstate
,action
anddata
paramsfailureHandler
Function An action handler that is passedstate
,action
anddata
params
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
A function that creates an API action handler that sets a path in the state with the returned data if a request succeeds.
path
String The path in the state to set with the returned datatransform
Function? A function that determines the data that is set in the state. Passedaction
andstate
params.
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
A function that creates an API action handler that sets a path in the state with the returned error if a request fails.
path
String The path in the state to set with the returned errortransform
Function? A function that determines the data that is set in the state. Passedaction
andstate
params.
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
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.
path
String The path in the state to set with the returned data on successpath
String The path in the state to set with the returned error on failuretransform
Function? A function that determines the success data that is set in the state. Passedaction
andstate
params.transform
Function? A function that determines the error data that is set in the state. Passedaction
andstate
params.
handleActions({
// This will do the same thing as the example for handleResponse
[apiActions.fetchUser]: setOnResponse('currentUser', 'userFetchError')
})
Returns Function An action handler
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
// An example action creator
function fooAction () {
return {
[LP_API]: {
url: 'http://foo.com/posts',
requestAction: 'REQUEST',
successAction: 'SUCCESS',
failureAction: 'FAILURE',
}
}
}
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.
type
String A unique key that will be used to identify the request internally in reduxdefinition
(Object | Function) An object of config options for the adapter, or a function that returns config options.
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.
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 ofunauthorized
.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
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
// 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'
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'
// 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'
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.
-
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 objectoptions.delay
Number Time (in ms) to delay the API request. Particularly useful when attempting to simulate loading states. (optional, default0
)
// ** 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.