1.1.5 • Published 2 years ago

@pure180/re-con v1.1.5

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

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

Typedefs

Timing : enum

Kind: global enum
Read only: true
Properties

NameType
Timing.Afterafter
Timing.Beforebefore

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

Kind: global function

useSelectorBase(Context, key) ⇒

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

ParamTypeDescription
ContextContext.<AppContextValue.<State, Item, ActionType>>The state Context object
keystringThe key of the state property

createSelectorHook(Context) ⇒

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

ParamTypeDescription
ContextContext.<AppContextValue.<State, Item, ActionType>>The state Context object

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

Kind: global function

ParamType
timingTiming
stateAppState
actionActionReturn
middlewareArray.<Middleware>

createAppStateProvider(Context) ⇒ React.FunctionComponent

Kind: global function

ParamTypeDescription
ContextReact.ContextApplication state context

Action ⇒ ActionReturn

Kind: global typedef

ParamTypeDescription
typeActionTypethe string / action type the reducer is acting on
payloadPayloadObject that mutates the State.

ActionReturn : Object

Kind: global typedef
Properties

NameTypeDescription
typeActionType | stringthe string / action type the reducer is acting on
payloadPayloadObject that mutates the state

Actions : Object.<string, Action>

Kind: global typedef

BaseState : Object

Kind: global typedef
Properties

NameTypeDescription
reducerReducerthe reducer to mutate the state
stateObject | Array | Stringthe state object

AppState : Object.<string, BaseState>

Kind: global typedef

AppStateProviderProps : Object

Kind: global typedef
Properties

NameTypeDescription
logbooleanShould log the application state to the console.
middlewareArray.<Middleware> | undefinedArray of middleware functions that
stateAppStateObject that holds the default state.

AppContextValue : Object

Kind: global typedef
Properties

NameTypeDescription
dispatchfunction
middlewareArray.<Middleware> | undefined
stateAppState

MiddlewareReturnFunction ⇒ AppState

Kind: global typedef

Middleware ⇒ Array.<Timing, MiddlewareReturnFunction>

Kind: global typedef

ParamTypeDescription
stateAppStatethe current state object
actionActionReturnthe current action

Reducer : function

Kind: global typedef

ParamTypeDescription
stateStatestate that can be mutated by the reducer.
actionActionReturnObject that should mutate the state.

AppStateProvider ⇒ React.FunctionComponent

Kind: global typedef

ParamType
propsPropsWithChildren.<AppStateProviderProps>
1.1.5

2 years ago

1.1.4

2 years ago

1.1.3

2 years ago

1.1.2

2 years ago

1.1.1

2 years ago

1.1.0

2 years ago

1.0.1

3 years ago

1.0.0

3 years ago