S
S
stepan1322020-09-28 20:35:46
typescript
stepan132, 2020-09-28 20:35:46

How to type dispatch functions?

There was a problem with typescript and function dispatch, I don't know what type to apply. Here is the action code where the error occurs:

import { Dispatch } from 'redux'
import { db } from '../../index'

import loadPatternsCreator from './actionCreator'
import loadPatternsActionType from './actionType'

import setError from '../setError'
import setErrorActionType from '../setError/actionType'

const loadPatterns = (term: string) => (dispatch: Dispatch<loadPatternsActionType | setErrorActionType>) => {
  try {
    dispatch(loadPatternsCreator([{}])) // эта функция сразу возвращает объект
  } catch (e) {
    dispatch(setError(e.message)) // здесь возникает ошибка, т.к. setError возвращает функцию
  }
}

export default loadPatterns

here is the setError action code:
import { Dispatch } from 'redux'
import setErrorActionType from './actionType'
import setErrorCreator from './actionCreator'

const setError = (msg: string) => (dispatch: Dispatch<setErrorActionType>) => {
  dispatch(setErrorCreator(msg))
}

export default setError

What type should be used? Thanks in advance for your reply.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Belyaev, 2020-09-28
@bingo347

do this: setError(e.message)(dispatch)instead of

dispatch(setError(e.message)) // здесь возникает ошибка, т.к. setError возвращает функцию
and everything will be right at once

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question