Untitled

mail@pastecode.io avatar
unknown
plain_text
18 days ago
1.5 kB
2
Indexable
Never
import {
  createSlice,
  Draft,
  PayloadAction,
  SliceCaseReducers,
  ValidateSliceCaseReducers,
} from '@reduxjs/toolkit'
import { initValue, resetValue, setValue } from './core'

type SetParamsArgs = {
  path?: string
  value: any
}

type BaseSliceActions<T> = {
  initValue: (state: Draft<T>) => void
  setValue: (state: Draft<T>, action: PayloadAction<SetParamsArgs>) => void
  resetValue: (state: Draft<T>) => void
}

type CreateStoreSliceOptions<T, Reducers extends SliceCaseReducers<T>> = {
  initialFn: () => T
  name: string
  reducers: ValidateSliceCaseReducers<T, Reducers>
}

export const createStoreSlice = <T extends object, TReducers extends SliceCaseReducers<T>>({
  initialFn,
  name,
  reducers,
}: CreateStoreSliceOptions<T, TReducers>) => {
  return createSlice({
    initialState: initialFn(),
    name,
    reducers: {
      initValue: (state) => {
        initValue({ state, initialState: initialFn() })
      },
      setValue: (state, action: PayloadAction<SetParamsArgs>) => {
        setValue({
          state,
          path: action.payload.path,
          value: action.payload.value,
        })
      },
      resetValue: (state) => {
        resetValue(state)
      },
      ...reducers,
    } as BaseSliceActions<T> & ValidateSliceCaseReducers<T, TReducers>,
  })
}

const a = createStoreSlice({
  initialFn: () => ({ a: 1, b: 2 }),
  name: '',
  reducers: {
    test(){},
    test2(){}
  },
})
Leave a Comment