virzen / redux-normalize-axios-middleware

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Redux Normalize Axios Middleware

Normalize data using redux-axios-middleware and normalizr schema

Installation

yarn add redux-normalize-axios-middleware normalizr

Usage

Add normalizeAxiosMiddleware

import normalizeAxiosMiddleware from 'redux-normalize-axios-middleware'

const store = createStore(testReducer, applyMiddleware(
  axiosMiddleware(axiosClient),
  normalizeAxiosMiddleware
))

Add normalizr schema to your action:

import { schema } from 'normalizr'

const fetchPosts = () => ({
  type: 'FETCH_POSTS',
  payload: {
    request: {
      url: API_URL
    }
  },
  normalize: {
    schema: new schema.Entity('posts'),
  }
})

This will normalize data and include ids of items:

{
  data: {
    posts: {
      items: { 1: { id: 1, title: 'title' } },
      allIds: [1],
    }
  },
  ...remainingAxiosData
}

If your data is nested you can use path option to specify what should be normalized. The remaining part of data outside of path will be omitted. path uses lodash/get format:

import { schema } from 'normalizr'

const fetchPosts = () => ({
  type: 'FETCH_POSTS',
  payload: {
    request: {
      url: API_URL
    }
  },
  normalize: {
    schema: [new schema.Entity('posts')],
    path: 'allPosts'
  }
})

This will normalize:

{
  allPosts: [{
    id: 1,
    title: 'title'
  }],
  someOtherData: 'lorem ipsum',
}

To:

{
  posts: {
    items: { 1: { id: 1, title: 'title' } },
    allIds: [1],
  }
}

About

License:MIT License


Languages

Language:JavaScript 100.0%