1.0.1 • Published 5 years ago

react-lazy-context v1.0.1

Weekly downloads
2
License
MIT
Repository
github
Last release
5 years ago

react-lazy-context

Installation

Using npm

npm i -S react-lazy-context

Using yarn

yarn add react-lazy-context

Usage

Reducers

Create reducers with an initial state. If the action is not recognized, the reducer must return state provided in the first argument.

const initialState = {
  count: 0,
};

const clicksReducers = (state = initialState, action) => {
  switch (action.type) {
    case 'INCREMENT_COUNT_BY_1':
      return {
        ...state,
        count: state.count + 1,
      };

    default:
      return state;
  }
};

export default clicksReducer;

Combine all reducers into a single reducer

import clicksReducer from './pathToClicksReducer';
import menuReducer from './pathToMenuReducer';
import authReducer from './pathToAuthReducer';

const rootReducer = {
  clicks: clicksReducer,
  menu: menuReducer,
  auth: authReducer,
};

export default rootReducer;

Tip: The key names provided in the rootReducer object will define the state key names. Using the example above, the state shape will be { clicks, menu, auth }.

Providing the Context

Import the rootReducer and pass it to LazyProvider

import React, { Component } from 'react';
import LazyProvider from 'react-lazy-context';

import rootReducer from './pathToRootReducer';

class App extends Component {
  render() {
    return (
      <LazyProvider reducers={rootReducer}>
        <YourComponentOrRoutes />
      </LazyProvider>
    );
  }
}

export default App;

Consuming the Context

Access the entire state and dispatch from any component by calling lazyConnect()

import React, { Component } from 'react';
import { lazyConnect } from 'react-lazy-context';

class ClicksCounter extends Component {
  render() {
    const { state, dispatch } = this.props;
    return (
      <div>
        <h1>Clicks Count: {state.clicks.count}</h1>
        <button onClick={() => dispatch({ type: 'INCREMENT_CLICKS' })}>
          Click Here
        </button>
        <hr />
      </div>
    );
  }
}

export default lazyConnect(ClicksCounter);

Tip: Use class based or functional components :)

Pass only a certain part of the state to a component with dispatch actions by creating a function called contextToProps

import React from 'react';
import { lazyConnect } from 'react-lazy-context';

const ClicksCounter = props => {
  const { count, incrementClicks } = props;
  return (
    <div>
      <h1>Clicks Count: {count}</h1>
      <button onClick={incrementClicks}>Click Here</button>
      <hr />
    </div>
  );
};

const contextToProps = context => {
  const { state, dispatch } = context;
  return {
    count: state.clicks.count,
    incrementClicks: () => dispatch({ type: 'INCREMENT_CLICKS' }),
  };
};

export default lazyConnect(ClicksCounter, contextToProps);

Asynchronous Actions

In the example below, the fetchTodos function will dispatch 2 actions and fetch data from an API. The first action can be used to set the loading state to true and the second can set the loading to false and supply the state with the data provided by the API.

const fetchTodos = () => {
  return dispatch => {
    dispatch({ type: 'FETCH_TODOS' }); // Show a loading animation if desired
    fetch(`https://jsonplaceholder.typicode.com/todos`)
      .then(response => response.json())
      .then(json => {
        dispatch({ type: 'FETCH_TODOS_SUCCESS', payload: json });
      });
  };
};

Use the fetchTodos() function by calling dispatch()

const contextToProps = context => {
  const { state, dispatch } = context;
  return {
    todos: state.todos.data,
    fetchTodos: () => dispatch(fetchTodos()),
  };
};