Giter Site home page Giter Site logo

redux-fetch-duck's Introduction

redux-fetch-duck

Simple and flexible API for creating a redux duck to manage a single fetch request, features loading and error states.

Instalation

It requires redux and thunk middleware.

$ yarn add redux-fetch-duck redux redux-thunk

Example

Simple usage

You can create a single file module in your project

// users.js
import { thunkCreator, withFetch } from 'redux-fetch-duck';

// This function is in charge of fetching the data.
// It must return a promise
const callApi = () => fetch('api.example.com/users');
// Selectors funcions depends on wich library is doing the request. They are optional.
const dataSelector = res => res.data;
const errorSelector = err => err.body.message;

// This functions returns the thunk ready to be disptched.
export const getUsers = thunkCreator('users', callApi, dataSelector, errorSelector)

// creates the duck reducer. 
export default withFetch('users')();

Combine the new duck reducer

// rootReducer.js
import { combineReducers } from 'redux';
import users from './users';

export default combineReducers({
  users,
})

This generate the state initial state

{
  users: {
    data: null,
    loading: false,
    error: null,
  }
}

Finally dispatch the thunk if you want to fetch de data

import React from 'react';
import { connect } from 'react-redux'
import { getUsers } from '../redux/users';

class Container extends React.Component {
  componentWillMount() {
    if (!this.props.users) {
      this.props.dispach(getUsers());
    }
  }
  render() {
    const { loading, users, error } = this.props;
    if (loading) return <div>Loading ...</div>;
    if (error) return <div>Cant fethc data, error: {error}</div>
    return (
      <div>
        {users}
      </div>
    )
  }
}

export default connect(state => ({
  loading: state.users.loading,
  error: state.users.error,
  users: state.users.data,
})(Container);

Extend your reducer

If you need a more complex state for your fetching resource you can import the types and action creators.

// users.js
import { thunkCreator, withFetch, types, actionCreators } from 'redux-fetch-duck';

// return an object with keys request, success, failure
const fetchTypes = types('users');

// this reducer will count the number of calls to the API
const calls = (state = 0, action) => {
  switch (action.type) {
    case fetchTypes.request:
      return state + 1;
    default:
      return state;
  }
};

// pass the reducer to be combined, it calls combineReducer under the hood.
export default withFetch('users')({ calls })

The new initial state will be

{
  users: {
    data: null,
    loading: false,
    error: null,
    calls: 0,
  }
}

API

You can find the api documentation here

Motivation

This module aims to reduce the boilerplate generated when you adopt this common pattern in Redux based apps.

Test

The test suite requires Jest, clone the repo, install the dependencies and then run the tests.

$ yarn
$ yarn test

Contribution

Feel free to create an Issue or even a pull request. You can email me at [email protected]. I'd love to hear your feedback.

License

MIT

redux-fetch-duck's People

Contributors

ivanwolf avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.