Skip to content

glarivie/redux-request

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

13 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

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)),
  })

About

Simple Redux API fetch middleware

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published