@pure180/re-con
TypeScript icon, indicating that this package has built-in type declarations

1.1.5 • Public • Published

React Context Application State Management

This package provides a basic functionality to manage your react application state with the Facebook house made context API.

Working example: https://codesandbox.io/s/pure180-re-con-example-se718

I would appreciate any comment or suggestion, please let me know what you think.

Table of Contents

Installation

npm i @pure180/re-con

or

yarn add @pure180/re-con

Usage

Create a file for all configurations that controls the state handling.

e.g.: ./src/State.ts

import {
  AppState,
  BaseState,
  createAppStateContext,
  createAppStateProvider,
  createSelectorHook,
  Middleware,
} from '@pure180/re-con';

// Enum values which describes all available state properties
export enum StateKeys {
  Item = 'item',
}

// Enum values that describes the actions for on reducer
export enum EnumActions {
  Change = 'change',
}

// Describes one state object
export type StateObject = {
  item: string;
};

// Describes the hole state object including the reducer.
export interface State {
  [StateKeys.Item]: BaseState<StateObject, EnumActions>;
}

// Create the application Context which we will use later to create the
// provider or gaining access to the whole State-Context object of your
// application.
export const AppContext = createAppStateContext<
  State,
  State[keyof State]['state'],
  EnumActions
>();

// Create the application state provider that gives the react element
// children the ability to access the application state.
export const AppStateProvider = createAppStateProvider<
  State,
  State[keyof State]['state'],
  EnumActions
>(AppContext);

// Create the selector hook which is able to access one state object
// including the dispatch function.
export const useSelector = (key: keyof State) =>
  createSelectorHook(AppContext)(key);

// Create a default state including your reducer
export const defaultState: AppState<
  State,
  State[keyof State]['state'],
  EnumActions
> = {
  [StateKeys.Item]: {
    reducer: (state, action) => {
      switch (action.type) {
        case EnumActions.Change:
          return {
            ...state,
            ...action.payload,
          };
        default:
          return state;
      }
    },
    state: {
      item: 'myValue',
    },
  },
};

// Create a middleware that should run after the state mutation
const middlewareAfterMutation: Middleware<State, State[keyof State]['state'], EnumActions> =
  (state, action) => [Timing.After, () => {
    if (action.type === EnumActions.Change) {
      state[StateKeys.Item].state.item = 'change value after mutation'
    }
    return state;
  }
];

export const middleware: Middleware<State, State[keyof State]['state'], EnumActions>[] = [
  middlewareAfterMutation,
];

Apply the State Context Provider to your application.

e.g.: ./src/index.tsx

import React, { useCallback } from 'react';

import {
  AppStateProvider,
  defaultState,
  EnumActions,
  middleware,
  StateKeys,
  useSelector,
} from './State';

const ComponentWithSelectorHook: React.FunctionComponent = () => {
  const [state, dispatch] = useSelector(StateKeys.Item);

  const handleClick = useCallback(() => {
    const item = 'New Item Value';

    dispatch({
      type: EnumActions.Change,
      payload: { ...state, item },
    });
  }, [dispatch, state]);

  return (
    <div>
      <p>{state.item}</p>
      <button onClick={handleClick}>Click to change the State</button>
    </div>
  );
};

export const AppWithStateContextProvider: React.FunctionComponent = () => (
  <AppStateProvider state={defaultState} middleware={middleware}>
    <ComponentWithSelectorHook />
  </AppStateProvider>
);

export default AppWithStateContextProvider;

Functions

createAppStateContext()Context.<AppContextValue.<State, Item, ActionType>>

Creates the basic Application State Context;

useSelectorBase(Context, key)

Basic Selector hook to access the state context

createSelectorHook(Context)

Creates the selector hook to access a property of the global state given by a key e.G.:

const useSelector = createSelectorHook(YourAppStateContext);
resolveMiddleware(timing, state, action, middleware)AppState

Resolving the middleware to mutate the application state before or after the reducer takes places.

createAppStateProvider(Context)React.FunctionComponent

Function to create the React App State Context Provider

Typedefs

ActionActionReturn

Function type that describes an action.

ActionReturn : Object

Object describing the state change

Actions : Object.<string, Action>
BaseState : Object
AppState : Object.<string, BaseState>

Basic state object that gets mutated.

AppStateProviderProps : Object

Default app state provider properties

AppContextValue : Object

the default context properties

MiddlewareReturnFunctionAppState

the 2. argument that gets returned by the Middleware

MiddlewareArray.<Timing, MiddlewareReturnFunction>
Reducer : function

Function type that describes the reducer

AppStateProviderReact.FunctionComponent

Timing : enum

Enum describing the time an middleware should be called

Kind: global enum
Read only: true
Properties

Name Type
Timing.After after
Timing.Before before

createAppStateContext() ⇒ Context.<AppContextValue.<State, Item, ActionType>>

Creates the basic Application State Context;

Kind: global function

useSelectorBase(Context, key) ⇒

Basic Selector hook to access the state context

Kind: global function
Returns:

[AppState, (action: ActionReturn<ActionType, Item>) => void] - Returns a tuple of the selected state and the dispatch function

Param Type Description
Context Context.<AppContextValue.<State, Item, ActionType>>

The state Context object

key string

The key of the state property

createSelectorHook(Context) ⇒

Creates the selector hook to access a property of the global state given by a key e.G.:

const useSelector = createSelectorHook(YourAppStateContext);

Kind: global function
Returns:

[AppState, (action: ActionReturn<ActionType, Item>) => void] - Returns a tuple of the selected state and the dispatch function

Param Type Description
Context Context.<AppContextValue.<State, Item, ActionType>>

The state Context object

resolveMiddleware(timing, state, action, middleware) ⇒ AppState

Resolving the middleware to mutate the application state before or after the reducer takes places.

Kind: global function

Param Type
timing Timing
state AppState
action ActionReturn
middleware Array.<Middleware>

createAppStateProvider(Context) ⇒ React.FunctionComponent

Function to create the React App State Context Provider

Kind: global function

Param Type Description
Context React.Context

Application state context

Action ⇒ ActionReturn

Function type that describes an action.

Kind: global typedef

Param Type Description
type ActionType

the string / action type the reducer is acting on

payload Payload

Object that mutates the State.

ActionReturn : Object

Object describing the state change

Kind: global typedef
Properties

Name Type Description
type ActionType | string

the string / action type the reducer is acting on

payload Payload

Object that mutates the state

Actions : Object.<string, Action>

Kind: global typedef

BaseState : Object

Kind: global typedef
Properties

Name Type Description
reducer Reducer

the reducer to mutate the state

state Object | Array | String

the state object

AppState : Object.<string, BaseState>

Basic state object that gets mutated.

Kind: global typedef

AppStateProviderProps : Object

Default app state provider properties

Kind: global typedef
Properties

Name Type Description
log boolean

Should log the application state to the console.

middleware Array.<Middleware> | undefined

Array of middleware functions that

state AppState

Object that holds the default state.

AppContextValue : Object

the default context properties

Kind: global typedef
Properties

Name Type Description
dispatch function
middleware Array.<Middleware> | undefined
state AppState

MiddlewareReturnFunction ⇒ AppState

the 2. argument that gets returned by the Middleware

Kind: global typedef

Middleware ⇒ Array.<Timing, MiddlewareReturnFunction>

Kind: global typedef

Param Type Description
state AppState

the current state object

action ActionReturn

the current action

Reducer : function

Function type that describes the reducer

Kind: global typedef

Param Type Description
state State

state that can be mutated by the reducer.

action ActionReturn

Object that should mutate the state.

AppStateProvider ⇒ React.FunctionComponent

Kind: global typedef

Param Type
props PropsWithChildren.<AppStateProviderProps>

Package Sidebar

Install

npm i @pure180/re-con

Weekly Downloads

1

Version

1.1.5

License

MIT

Unpacked Size

73.1 kB

Total Files

28

Last publish

Collaborators

  • pure180