score:0

i made some changes in your code to fix issues. here is the updated code.

// reducerfactory.ts
export interface actionhandler<s, a> {
  [actiontype: string]: genericreducer<s, a>
}

export type genericreducer<s, a> = (state: s, action: a) => s

const reducerfactory = <s, a extends { type: string }>(
  initialstate: s,
  handlers: actionhandler<s, a>
): genericreducer<s, a> => {
  return (state: s = initialstate, action: a): s => handlers[action.type]?.(state, action) || state
}

export default reducerfactory

// actions.ts
export enum loadingactions {
  add_loading_token = 'add_loading_token',
  remove_loading_token_with_key = 'remove_loading_token_with_key',
}

export interface addloadingtokenaction {
  type: typeof loadingactions.add_loading_token
  payload: loadingtoken
}

export interface removeloadingtokenwithkeyaction {
  type: typeof loadingactions.remove_loading_token_with_key
  payload: loadingtoken
}

type actions = addloadingtokenaction | removeloadingtokenwithkeyaction

// handler.addloadingtoken.ts
const addloadingtoken: genericreducer<loadingstate, actions> = (state, action:actions): loadingstate => {
  return {
      ...state,
      loadingtokens: [...state.loadingtokens, action.payload],
  }
}

export { addloadingtoken }

// handler.removeloadingtokenwithkey.ts
const removeloadingtokenwithkey: genericreducer<loadingstate, actions> = (
  state,
  action: actions
) => ({
  ...state,
  loadingtokens: [...state.loadingtokens].filter(loadingtoken => loadingtoken.key !== action.payload.key),
})

export { removeloadingtokenwithkey }

// index.ts
export interface loadingtoken {
  key: string
  scope: string
  message: string
}

export interface loadingstate {
  loadingtokens: loadingtoken[]
}

const initialloadingstate: loadingstate = {
  loadingtokens: [],
}

const loadinghandlers: actionhandler<loadingstate, actions> = {
  [loadingactions.add_loading_token]: addloadingtoken,
  [loadingactions.remove_loading_token_with_key]: removeloadingtokenwithkey,
}

const loadingreducer = reducerfactory<loadingstate, actions>(initialloadingstate, loadinghandlers)

let me know, if you still face any problem.

as suggested by @phry using redux-toolkit will make your life lot easier. the article you linked was written in mid 2019. things have changed a lot since then. take a look at these new articles to make your life easier.

  1. redux-toolkit
  2. throw-out-redux-use-redux-toolkit

Related Query

More Query from same tag