2.0.2 • Published 2 years ago

next-context-store v2.0.2

Weekly downloads
2
License
ISC
Repository
github
Last release
2 years ago

next-context-store

use new context api as store | 使用新的context api做数据仓库

  • redux is single store, I want some simple multi store | redux 是单仓库的,我需要一个简单的多仓库
  • new context api is rather an injector than store | 相比store新的context api更像是一个injector,作为store使用并不方便

so I start this, for at times I need small stores to hold shered data cross components, for example store data only for shared in parts of one page, and I don't want all the data for every page to go inside redux | 所以我开始了这个项目,因为有时候我需要用一些小仓库来保持跨组件的数据,例如仅限某个页面使用的数据,我并不想让所有页面的数据都放到 redux

try it out: https://codesandbox.io/s/next-context-store-50sjq

basic useage | 基础使用

import { createStore } from 'next-context-store'

const CounterCtx = createStore(0)
export const Counter = () => {
  return <CounterCtx.Provider> 
    <CounterCtx.Consumer>{
      ([loading, value, error, dispatch]) => <div>
        <pre>{
          JSON.stringify({ loading, value, error }, null, 2)}</pre>
        <button onClick={() => dispatch(x => x + 1)}>+1</button>
        <button onClick={() => dispatch(async () => {
          await new Promise(r => setTimeout(r, 1000))
          return x => x + 1
        })}>+1 async</button>
      </div>
    }</CounterCtx.Consumer>
  </CounterCtx.Provider>
}

const UserCtx = createStore('')
export const Login = () => {
  let [loading, user, error, dispatch] = UserCtx.useContext()
  return <UserCtx.Provider>
    {user ? <>
      {user}|<button onClick={() => dispatch("")}>logout</button>
    </> : <button onClick={() => dispatch(async () => {
      await new Promise(r => setTimeout(r, 1000))
      return 'someone'
    })}>login</button>}|{loading ? '...loading' : ''}
  </UserCtx.Provider>
}

example usage | 使用示例: ./examples/basic/

APIs

createStore(initialValue,initialAction)

params

initialValue: T extends any initial value of store

initialAction: Action<T> optional, initial action

return value: obj object

obj.Provider: FC<{}> domain this store works

obj.Consumer : React.Consumer<[loading: boolean, value: T, error: any, dispatch: (fn: Action<T>) => void]>* to use the store

obj.useContext: ()=>[loading: boolean, value: T, error: any, dispatch: (fn: Action<T>) => void] hook to use this store

obj.Context: React.Context<[loading: boolean, value: T, error: any, dispatch: (fn: Action<T>) => void]> React Context if you need

about Action:

type Action<T> = T | ((v?: T) => T)
  | Promise<T> | ((v?: T) => Promise<T>)
  | ((val?: T) => Promise<(v?: T) => T>)
2.0.2

2 years ago

2.0.1

2 years ago

2.0.0

2 years ago

1.0.3

4 years ago

1.0.2

4 years ago

1.0.1

4 years ago

1.0.0

6 years ago