Skip to content

Feature Suggestion: setPropCaseReducer function for basic updates #2659

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Harris-Miller opened this issue Aug 30, 2022 · 3 comments
Closed

Comments

@Harris-Miller
Copy link

I'm sure that this caseReducer

(state: State, action: PayloadAction<T>) => {
  state.propName = action.payload;
};

Is common enough that @reduxjs/toolkit should supply a function abstraction of it

const setPropCaseReducer = <State, Prop extends keyof State>(prop: Prop) => (state: State, action: PayloadAction<State[Prop]>) => {
  state[propName] = action.payload;
};

type UserState = {
  email: string;
};

const initialState: UserState = {
  email: ''
};

const useSlice = createSlice({
  name: 'user',
  initialState,
  reducers: {
    setEmail: setPropCaseReducer<UserState>('email')
  }
});
@EskiMojo14
Copy link
Collaborator

EskiMojo14 commented Aug 30, 2022

this pattern is explicitly discouraged - reducers should be modeled as events and modify as many properties as is necessary.

@Harris-Miller
Copy link
Author

Harris-Miller commented Aug 30, 2022

¯\_(ツ)_/¯

@markerikson
Copy link
Collaborator

Yeah, this is similar to the answer I gave in #2658.

We actively don't want users to be writing a bunch of reducers that are all state.fieldName = action.payload all the time.

That's not to say you should never do this - I've even written a few of these myself over in the Replay codebase.

But it's a pattern we want users to minimize, rather than one we want to encourage.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants