• Stars
    star
    105
  • Rank 327,162 (Top 7 %)
  • Language
    JavaScript
  • License
    Other
  • Created almost 8 years ago
  • Updated almost 2 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Data fetching with redux made easy

READ ME

npm version

redux-io

redux-io is library for data management of network data in redux and ease of data use in react. Consists of middleware, reducers, action creators and helpers that provide:

  • JSON-API
  • normalized data in redux
  • async CRUD operations with redux actions
  • optimistic updates of redux
  • denormalizing data for easier use in react
  • data caching and supported compatibility with reselect
  • simple and expandable network resource configuration
  • data status, error handling and monitoring operations
  • [SOON] JSON payloads with normalizr schemas

Motivation

Redux is a great library, but itโ€™s not a framework. Itโ€™s based on simple concepts that enable the freedom to build, but without clear patterns. But how are you going to manage network data and organize it in store, make async requests, normalize data, handle errors, cache data, monitor data statuses? At Shoutem we developed platform based on react ecosystem in which we use redux for managing data. We learned a lot about problems and discovered practices that give answers to above questions. All that is used in development of redux-io library that we use everyday and enables us powerful data management.

Documentation

Getting started

Install redux-io:

$ npm install --save @shoutem/redux-io

Import middlewares apiMiddleware, apiStateMiddleware and add them to your createStore in applyMiddleware function from redux. We are internally using [[email protected]] (https://github.com/agraboso/redux-api-middleware/tree/next) as library for async network requests, so that is the reason you need to add both middlewares respectively.

Example:

import { applyMiddleware, compose, createStore } from 'redux';
import { apiMiddleware } from 'redux-api-middleware';
import { apiStateMiddleware } from '@shoutem/redux-io';
import createLogger from 'redux-logger';
import thunk from 'redux-thunk';
import reducer from './reducers'

const logger = createLogger();

const store = createStore(
  reducer,
  applyMiddleware(thunk, apiMiddleware, apiStateMiddleware, logger)
);

And you are ready to start organizing state, configuring network resources, manage data with actions and use them in react components. Next section gives short intro in usage of redux-io in most common use cases.

Usage

For example, you have json-api API endpoint that enables you to fetch items of type acme.items. You want to get most popular items, so endpoint http://api.test.com/items?sort=relevance returns you list of items sorted by popularity:

{
  "data": [
    {
      "type": "acme.items",
      "id": "1",
      "attributes": {
        "name": "Rocket",
      }
    },
    {
      "type": "acme.items",
      "id": "2",
      "attributes": {
        "name": "Helmet",
      }
    },
    ...
  ]
}

First you want to configure where fetched data will be placed in your state. Use storage as a normal reducer to define where in your state are instances of objects, and collection reducer to set place in the state for list holding ids of items that are popular. You are probably asking why do you need those two reducers, but idea is to keep data in redux state normalized. Normalization instances needs to be in one place in the state. However, you can reference it from mutliple parts in the state.

import { storage, collection } from `redux-api-state`;

combineReducers({
  items: storage('acme.items'),
  popularItems: collection('acme.items', 'popularItems'),
})

After that, you only need to dispatch find action to fetch popular items from API. Find action is based on redux-api-middleware, and only needs to additional params schema, and tag. Schema defines in which storage will fetched data end up, and tag defines which collection will fetch ids of objects.

import { find } from `redux-api-state`;

const config = {
  endpoint: 'http://api.test.com/items?sort=relevance',
  headers: {
    'Content-Type': 'application/vnd.api+json',
  },
};

dispatch(find(config, 'acme.items', 'popularItems'));

Upon dispatch, find will configure action by redux-api-middleware specification, and redux-api-middleware will

  1. Dispatch REQUEST action
  2. Make GET request on http://api.test.com/items?sort=relevance
  3. If request is successful dispatch SUCCESS action

You can see that it is by redux-api-middleware lifecycle. After which redux-api-state will listen on SUCCESS action and will act as:

  1. Validate SUCCESS action
  2. Unpack payload
  3. For each item in data will dispatch OBJECT_FETCHED
  4. Storage reducer will listen for OBJECT_FETCH and add it into map in state
  5. Dispatch COLLECTION_FETCHED
  6. Collection reducer will listen for COLLECTION_FETCHED and add items id into list
  7. Call next(action) for success action from redux-api-middleware

Storage reducer only adds an item if action is valid and schema value is equal to the action's schema. Collection reducer performs the same, but checks also tag value. That enable us to have multiple collections of objects, but only one storage with instances of objects. Here is the state after app finished fetching:

state: {
  items: {
    1: {
      "type": "acme.items",
      "id": "1",
      "attributes": {
        "name": "Rocket",
      }
    },
    2: {
      "type": "acme.items",
      "id": "2",
      "attributes": {
        "name": "Helmet",
      }
    },
  },
  popularItems: [1, 2, 3, ... ],
}

Tests

$ npm install && npm test

Acknowledgements

The package is based on concepts from ลฝeljko Rumenjak.

More Repositories

1

ui

Customizable set of components for React Native applications
JavaScript
4,895
star
2

shoutem.github.io

Supercharging React Native development
JavaScript
518
star
3

school

A new React Native app every 2 weeks. With tutorial :)
Objective-C
476
star
4

theme

Style your React Native components on one place
JavaScript
334
star
5

animation

Animate your React Native components
JavaScript
282
star
6

react-native-shopify

React Native bridge to Shopify Buy SDK
Java
262
star
7

extensions

Shoutem Extensions are common mobile app functionalities that supercharge your React Native development
JavaScript
224
star
8

fetch-token-intercept

JavaScript
67
star
9

platform

Shoutem platform
JavaScript
42
star
10

redux-composers

Additional reducer composers besides combineReducers from redux
JavaScript
34
star
11

cli

Shoutem CLI is a tool which helps you build Shoutem extensions faster
JavaScript
31
star
12

UrlBuilder

UrlBuilder is simple and powerful URL builder
C#
11
star
13

cordova-ios-twitter

Twitter plugin for cordova
JavaScript
9
star
14

extension-examples

Examples on extensions
JavaScript
4
star
15

api-sdk

JavaScript
2
star
16

FlurryLib

FlurryLib as uses by ShoutEm
Objective-C
2
star
17

facebook-ios-sdk

Facebook connect SDK with SSO turned off
Objective-C
1
star
18

react-native-calendar-manager

Objective-C
1
star
19

google-admob-ios-sdk

Objective-C
1
star
20

mockup_config

Mockup Config
Python
1
star
21

scriptem-py

A collection of useful shoutem scripts
Python
1
star
22

GTM

GTM as used by ShoutEm
Objective-C
1
star
23

OAuthConsumer

Objective-C
1
star
24

PLCrashReporter

git based checkout of plcrashreporter
Objective-C
1
star
25

ZBar

ShoutEm mirror of ZBar SDK repository
Objective-C
1
star
26

Three20

ShoutEm modification of Three20 library
Objective-C
1
star
27

MoPubSDK

Shoutem modifications to MoPubSDK
Objective-C
1
star
28

string-additions-for-html

As used by ShoutEm
Objective-C
1
star