luki512
luki512

Reputation: 237

Redux trigger reducer if value not changing

I've got a reducer function like the following:

        nextStep: (state) => {
            if (state.currentStep < state.totalSteps && state.currentStepValid) {
                state.currentStep += 1;
            }
        },

I'm listening to changes with the "useSelector" hook and I need to trigger a change even if the value doesn't change when dispatch is called. How is it possible to implement this?

Best regards!

Upvotes: 0

Views: 149

Answers (1)

Ashwel
Ashwel

Reputation: 1250

At first you must create store and add your reducer to createStore method

import todoApp from './reducers'

const store = createStore(todoApp)

Then implement your reducer as function, which consume two params prevState and actions and return next state based on action, like this in basic example Basic tutorial

import { VisibilityFilters } from './actions'

const initialState = {
  visibilityFilter: VisibilityFilters.SHOW_ALL,
  todos: []
}

function todoApp(state, action) {
  if (typeof state === 'undefined') {
    return initialState
  }

  // For now, don't handle any actions
  // and just return the state given to us.
  return state
}

In your code snippet, you aren't returning next state instead you are modify prev state.

You must write something like that:

nextStep: (state) => {
            if (state.currentStep < state.totalSteps && state.currentStepValid) {
                return {
                     ...state,
                     currentStep: state.currentStep + 1
                };
            } else {
                return state;
            }
        },

Upvotes: 1

Related Questions