Home > Enterprise >  How can I increment value if condition matches by Redux?
How can I increment value if condition matches by Redux?

Time:08-30

I am newbie about redux. I want to increment state by one when condition matches. Condition is true, i checked on the console. This is action;

if(btn.target.value == answer) {
            dispatch(calculate(prev => prev  1))
}

This is state;

export const scoreSlice = createSlice({
name: "score",
initialState: {value: 0}, 
reducers: {
    calculate: (state,action) => {
        state.value = action.payload
    }
}

output on the console;

prev => prev   1

CodePudding user response:

when you dispatch action, pass the number that you want to add to your value

if (btn.target.value == answer) {
  dispatch(calculate(1))
}

in reducer function => action.payload represents anything you pass to this function while dispatching it (action.payload = 1 here)

const reducers = {
  calculate: (state, action) => ({
    ...state, // copy original state
    value: state.value   action.payload
  })
}
  • Related