0

I need to make redux action and then use state to update my url. I have tried to make a promise:

  const opa = (type: string, checked: boolean) => (
    dispatch: any,
    getState: any   ) =>
    Promise.resolve().then(() => {
      return dispatch(sidebarEmploymentTypeActions.setType(type, checked))
    })

And then use it:

  const handleEmploymentTypeChange = (type: string, checked: boolean) => {
    //@ts-ignore
    dispatch(opa(type, checked)).then(console.log(employmentType))
  }

But console.log returns previous state. My action:

export const setType = (type: string, checked: boolean) => {
  return {
    type: sidebarEmploymentType.SET_TYPE,
    employmentType: type,
    checked
  }
}

And reducer:

const sidebarEmploymentType: Reducer = (
  state = defaultState,
  { type, employmentType, checked }
) => {
  switch (type) {
    case sidebarEmploymentTypeType.SET_TYPE:
      return {
        ...state,
        [employmentType]: {
          checked: checked,
          label: state[employmentType].label,
        },
      }

    default:
      return state
  }
}

export { sidebarEmploymentType }

Root reducer:

export const rootReducer = combineReducers({

  sidebarEmploymentType
})

And store creation:

import thunk from 'redux-thunk'
    const store = createStore(
      persistReducer(persistConfig, rootReducer),
      composeEnhancers(applyMiddleware(thunk))
    )
domanskyi
  • 445
  • 1
  • 3
  • 11
  • you can look at when the data is changing from `getDerivedStateFromProps` or `componentDidUpdate`. Why do you want to chain a `.then` on a dispatch? – John Ruddell Aug 26 '19 at 17:51
  • Yep, sorry. Fixed it :) – domanskyi Aug 26 '19 at 17:51
  • Because in my case using of `.then` looks more clean. I want to update state of checkboxes and then redirect user according to new state in one method. – domanskyi Aug 26 '19 at 17:55
  • 1
    You should wait for the data to be passed to the component to update your state. This way it's pure. One way data flow. This is what redux is. If you need to redirect do that in the thunk after your dispatch – John Ruddell Aug 26 '19 at 17:58

0 Answers0