Emre YAZICI
Emre YAZICI

Reputation: 23

How can I increment value if condition matches by Redux?

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

Upvotes: 0

Views: 88

Answers (1)

Salwa A. Soliman
Salwa A. Soliman

Reputation: 746

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
  })
}

Upvotes: 1

Related Questions