Home  >  Q&A  >  body text

Does each attribute need a reducer?

<p>I'm following this tutorial to increment a number. </p> <p>It works, but now I want to implement it to about 100 configuration values. Do I need to copy counterSlice.js 100 times or do I need to replace the number with an object with 100 properties? </p> <p>counterSlice.js</p> <pre class="brush:php;toolbar:false;">export const counterSlice = createSlice({ name: 'counter', initialState: { value: 0, }, reducers: { increment: (state) => { // Redux Toolkit allows us to write "modification" logic in reducers. It doesn't actually change the state because it uses the Immer library, // It detects changes to "draft state" and generates a completely new immutable state based on those changes. // Additionally, these functions do not require a return statement. state.value = 1 }, decrement: (state) => { state.value -= 1 }, incrementByAmount: (state, action) => { state.value = action.payload }, }, }) // Generate action creators for each case reducer function export const { increment, decrement, incrementByAmount } = counterSlice.actions export default counterSlice.reducer</pre> <p><br /></p>
P粉124070451P粉124070451401 days ago384

reply all(1)I'll reply

  • P粉404539732

    P粉4045397322023-08-18 09:20:48

    In some cases it may be wise to explicitly create functions for each status field. But if you do have around 100 status fields, then you need to take a more general approach.

    I recommend including a key and value field in the payload of the reducer function.

    export const configSlice = createSlice({
      name: 'config',
      initialState: {},
      reducers: {
        setConfigValue: (state, action) => {
          const { key, value } = action.payload;
    
          state[key] = value;
        },
      },
    })

    reply
    0
  • Cancelreply