/reresource

Manage resources using redux

Primary LanguageTypeScript

logo

reresource

👋

Build Status Version Documentation Maintenance License: MIT Twitter: rcelha

Manage resources in redux maintaining a sane mind

Install

yarn add reresource

Usage

Configure your store

import { applyMiddleware, combineReducers, createStore } from "redux";
import { reducer as resources, saga as resourceSaga } from "reresource";
import createSagaMiddleware from "redux-saga";

function rootReducer(state = {}, action) {
  return state;
}

const sagaMiddleware = createSagaMiddleware();
export default createStore(
  combineReducers({ rootReducer, resources }),
  applyMiddleware(sagaMiddleware)
);
sagaMiddleware.run(resourceSaga);

Fetch resource

import React from 'react';
import { getResource, fetchResource } from 'reresource';

class UserRepr extends React.Component {
  componentDidMount() {
    this.props.fetchResource('users', service.fetchUser, 1);
  }

  render() {
    if (this.props.user.error) return <div>Error loading user</div>;
    if (this.props.user.loading) return <div>loading...</div>;
    return <div>{this.props.user.data.fullName}</div>;
  }
}

const mapStateToProps = (state, props) => ({
  user: getResource(state, 'users', props.id),
});

const mapDispatchToProps = {
  fetchResource,
};

Delete resource

import React from 'react';
import { getResource, fetchResource, deleteResource } from 'reresource';

class UserRepr extends React.Component {
  componentDidMount() {
    this.props.fetchResource('users', service.fetchUser, 1);
  }
  
  deleteResource() {
    const { user } = this.props;
    this.props.deleteResource('users', service.deleteUser, user.data.id);
  }

  render() {
    if (this.props.user.error) return <div>Error loading user</div>;
    if (this.props.user.loading) return <div>loading...</div>;
    return <div>{this.props.user.data.fullName}<button onClick={deleteResource}>Delete</button></div>;
  }
}

const mapStateToProps = (state, props) => ({
  user: getResource(state, 'users', props.id),
});

const mapDispatchToProps = {
  fetchResource,
  deleteResource,
};

Docs

  1. Data-flow
  2. Examples
    1. Fetch resource
    2. List resources
    3. Create resource
    4. Update resource
    5. Delete resource
  3. HOC
  4. API docs

Run tests

yarn test

Author

👤 Rodrigo Correa Alves

Show your support

Give a ⭐️ if this project helped you!

📝 License

Copyright © 2019 Rodrigo Correa Alves.

This project is MIT licensed.