1.0.4 • Published 6 years ago

@hqro/redux-request v1.0.4

Weekly downloads
-
License
MIT
Repository
github
Last release
6 years ago

Redux Request Middleware

Simple Redux API request middleware

Installation

yarn add @hqro/redux-request
import { createStore, applyMiddleware, compose } from 'redux'
import requestMiddleware from '@hqro/redux-request'

import reducers from './reducers'

const store = createStore(
  reducers,
  undefined, // Initial state
  compose(
    applyMiddleware(
      requestMiddleware,
    ),
  ),
)

export default store

Usage

// actions/users.js
const { API_URL } = process.env

const fetchAllUsers = token => ({
  type: '@@REQUEST/FETCH_ALL_USERS',
  url: `${API_URL}/users`,
  headers: { Authorization: token },
})

const createUser = data => ({
  type: '@@REQUEST/CREATE_USER',
  method: 'POST',
  url: `${API_URL}/user`,
  body: JSON.stringify(data),
  onSuccess: () => console.log('User created !'),
  onError: e => console.error(e),
})
// reducers/users.js
const initialState = {
  users: [],
}

const userReducer = (state = initialState, { type, payload }) => {
  switch (type) {
    case '@@REQUEST/FETCH_ALL_USERS_PENDING':
    case '@@REQUEST/FETCH_ALL_USERS_ERROR':
      return initialState
    case '@@REQUEST/FETCH_ALL_USERS_SUCCESS':
      return ({
        ...state,
        users: payload.data,
      })
    default:
      return state
  }
}

Using Redux-Thunk

// actions/users.js
const { API_URL } = process.env

const fetchAllUsers = (token, retries = 2) =>
  async dispatch => dispatch({
    type: '@@REQUEST/FETCH_ALL_USERS',
    url: `${API_URL}/users`,
    headers: { Authorization: token },
    onError: () =>
      retries && dispatch(fetchAllUsers(token, retries - 1)),
  })