GithubHelp home page GithubHelp logo

redux-crudo's Introduction

redux-crudo

Build Status Coverage Status

A package for writing convention-driven reducers and actions for Redux.

It provides, generic reducers and actions for all rest methods and a generic post methods: (create, read, update, delete, list and post).

Goal

The goal of this project is to handle all the hassle of writing reducers and actions for a REST API. Since most of the code will be the same overall the application it can be shared.

The idea is to provide generic reducers and action for the common redux pattern of REQUEST, SUCCESS, FAILURE.

It is meant to be use with redux-thunk middleware.

Disclaimer

This project was made initially to works with a Django Rest Framework Api and the axios library , so some behaviours (especially errors handling) might works better with DRF. Feel free to PR for more generic solutions.

State

Each resource will have it's own reducer creating the following state:

const initialState = {
  args: {},
  item: {},
  items: new Map(),
  error: false,
  errors: {},
  loading: false,
  status: "",
  statusCode: 0,
}
  • args: is set to action.payload in all REQUEST actions.
  • item: is the item in READ & UPDATE actions.
  • items: is a Map() used in LIST actions, For now Map() objects are sorted according to the API result and can be accessed by their uuid. For now only uuid keyed items are supported. TODO : handle any kind of primary key.
  • error: boolean if last request failed or not.
  • errors: set to response.data (if action is generated with the register method and used the standard api wrapper).
  • loading: set to true in REQUEST set to false in FAILURE or SUCCESS.
  • status: name of last action, e.g "create_request", "create_success", etc.
  • statusCode: http code response.

Reducers

Example of a reducer

/**
 * Account reducers.
 */
import { combineReducers } from "redux";
import { CREATE, READ, UPDATE, DELETE, LIST, POST } from "redux-crudo/utils";
import { apiReducer } from "redux-crudo/reducers";

// Handle read and update
export default const accountReducer = apiReducer("ACCOUNT", READ | UPDATE);

Actions

const AccountActions = apiActions("ACCOUNT", READ | UPDATE);

accountActions will contain the following action types:

READ_FAILURE: "ACCOUNT_READ_FAILURE"
READ_REQUEST: "ACCOUNT_READ_REQUEST"
READ_SUCCESS: "ACCOUNT_READ_SUCCESS"
UPDATE_FAILURE: "ACCOUNT_UPDATE_FAILURE"
UPDATE_REQUEST: "ACCOUNT_UPDATE_REQUEST"
UPDATE_SUCCESS: "ACCOUNT_UPDATE_SUCCESS"

And the following methods

readFailure: ƒ (errorCode, errors)
readRequest: ƒ (payload)
readSuccess: ƒ (payload)
updateFailure: ƒ (errorCode, errors)
updateRequest: ƒ (payload)
updateSuccess: ƒ (payload)

Assign a crud operation

import { apiActions, assignCrudMethod } from "redux-crudo/actions";
const AccountActions = apiActions("ACCOUNT", READ | UPDATE);
// Given that Services.Account.create is the api call method
AccountActions.create = assignCrudMethod(
    AccountActions,
    Services.Account.create,
    CREATE
);

Note on the api method.

Api methods must by async and behave like axios methods.

The assignCrudMethod return an action that behave like this:

try {
    const response = await apiMethod(args);
    dispatch(SUCCESS(response.status, response.data));
} catch (error) {
    dispatch(FAILURE(error.response.status, error.response.data));
}

So the API method should return a {response: { data: "...", status: 200}} object on success. And raise a error = {response: { data: "...", status: 200}} on failure.

Warning on actions

API methods should only take one context object and destructuring it.

Example:

Services.Account.update. = async ({ id, data }) => {
    return axios.patch(`${ACCOUNT_DETAIL}${id}/`, data);
}

Pay attention when writing mapDispatchToProps to not destructuring too early.

const mapDispatchToProps = dispatch => ({
    handleSubmit: {(id, data)} => dispatch(AccountActions.update({ id, data }))
    // or
    handleSubmit: payload => dispatch(AccountActions.update(payload))
});

redux-crudo's People

Contributors

renovate-bot avatar renovate[bot] avatar rolandkuku avatar luxcem avatar dependabot[bot] avatar nsuarezcanton avatar floriancargoet avatar

Stargazers

 avatar  avatar  avatar

Watchers

James Cloos avatar

redux-crudo's Issues

Standardization of API calls.

The way the current register function works is that it will send the action payload to the API method.
The drawback of that is that API method cannot take more than one arguments.

I try to use the rest parameter syntax without success in the past.

I think we should enforce the use of "context" object with destructing (like the props in react).

const FeedbackApi = {
    create: async ({ data }) => Api.post(REWARD_CREATE, data),
    list: async ({ id }) => Api.get(`${REWARD_LIST}${id}/`),
    patch: async ({ uuid, data }) =>
        Api.patch(`${REWARD_DETAIL}${uuid}/`, data),
};

instead of

const FeedbackApi = {
    create: async (data) => Api.post(REWARD_CREATE, data),
    list: async (id) => Api.get(`${REWARD_LIST}${id}/`),
    patch: async (uuid, data) =>
        Api.patch(`${REWARD_DETAIL}${uuid}/`, data),
};

It's what we are doing but it should be a clear statement in the documentation (README).

Use of constants instead of string in methods parameters.

I think we should replace the methods parameter with a combination of constants.
As of now it's:

export function apiReducer(resource, methods = "crudlp", options = {})

I suggest to use a set of constants:

export const CREATE = 1;
export const READ = 2;
export const UPDATE = 4;
export const DELETE = 8;
export const LIST = 16;
export const POST = 32;

It uses a binary tricks to allows a combination of methods.

Calls will be:

export function apiReducer(resource, CREATE | READ | UPDATE)
// We can replace
if (methods.indexOf("c") > -1);
// With
if (methods & CREATE);

Action Required: Fix Renovate Configuration

There is an error with this repository's Renovate configuration that needs to be fixed. As a precaution, Renovate will stop PRs until it is resolved.

Error type: undefined. Note: this is a nested preset so please contact the preset author if you are unable to fix it yourself.

Dependency Dashboard

This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.

Warning

These dependencies are deprecated:

Datasource Name Replacement PR?
npm babel Unavailable

Edited/Blocked

These updates have been manually edited so Renovate will no longer make changes. To discard all commits and start over, click on a checkbox.

Detected dependencies

npm
package.json
  • immutability-helper ^3.0.1
  • immutable ^3.8.2
  • prop-types ^15.6.2
  • babel 6.23.0
  • babel-cli 6.26.0
  • babel-core 6.26.3
  • @babel/eslint-parser 7.25.1
  • babel-jest 29.7.0
  • babel-plugin-root-import 6.6.0
  • babel-plugin-transform-object-rest-spread 6.26.0
  • babel-preset-env 1.7.0
  • coveralls 3.1.1
  • eslint 9.9.1
  • eslint-config-airbnb 19.0.4
  • eslint-plugin-import 2.29.1
  • eslint-plugin-jsx-a11y 6.9.0
  • eslint-plugin-react 7.35.0
  • jest 29.7.0
  • prettier 3.3.3
travis
.travis.yml
  • node 10

  • Check this box to trigger a request for Renovate to run again on this repository

Improving the register function

Right now the apiActionType have a register method to register a new action linked to an API call.

I found it confusing :

FeedbackActions.register("list", FeedbackApi.list, "list");

There is twice the "list" word, register is part of the object FeedbackActions but it's not an action.

What I suggest:

  1. Rename apiActionType() to apiActions() since reducer is only apiReducer().
  2. Extract the register method in something else that will work like that:
// Given that Services.Feedback.list is the api call method
FeedbackActions.list = assignApiToList(FeedbackActions, Services.Feedback.list);

The drawback of that is that we have a function for every method (Create, Read, Update, Delete, List, Post)

An other solution would be to have a constant for each method:

// Given that Services.Feedback.list is the api call method
FeedbackActions.list = assignApiMethod(FeedbackActions, Services.Feedback.list, LIST);

The assignXXX method needs the FeedbackActions object to correctly dispatch the "Request", "Success" and "Failure" actions.

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.