@enqode/ts-reducer
TypeScript icon, indicating that this package has built-in type declarations

1.0.5 • Public • Published

Usage

import { createStore, AnyAction, Dispatch } from 'redux'
import { create } from './../src/index'

/**
 * Defining the state
 */

type Message = {
  username: string
  message: string
}

type ChatState = {
  messages: Message[]
}

const initialState: ChatState = {
  messages: []
}


/**
 * Creating the reducer
 */

type SendMessage = {
  username: string
  message: string
}

const sendMessage = create<ChatState, SendMessage>('SEND_MESSAGE', (state, message) => {
  return{
    ...state,
    messages:[
      ...state.messages,
      message
    ]
  }
})


/**
 * Using the reducer inside your rootReducer
 */

const reducersMap = {
  [sendMessage.type]: sendMessage.reducer
}

const rootReducer = (state: ChatState = initialState, action: AnyAction) => {
  if(reducersMap[action.type]){
    return reducersMap[action.type](state, action.payload || null)
  }
  return state
}

const store = createStore(rootReducer)


/**
 * How to dispatch actions
 */

// using store.dispatch directly
sendMessage.createDispatch(store.dispatch)({
  username: 'enqode',
  message: 'Hey there!',
})

// using react-redux's connect function
const mapDispatchToProps = (dispatch: Dispatch) => ({
  sendMessage: (message: string) => sendMessage.createDispatch(dispatch)({
    username: 'enqode',
    message
  })
})

Readme

Keywords

none

Package Sidebar

Install

npm i @enqode/ts-reducer

Weekly Downloads

1

Version

1.0.5

License

MIT

Unpacked Size

11.5 kB

Total Files

17

Last publish

Collaborators

  • enqode