Search code examples
reactjstypescriptreduxredux-saga

Redux-Saga call effect always ends on catch block


I'm using Google Translate API and translating texts before populating store with some data, but using call() effect to translate effects, the response always go into catch block, even when the translate request is successful

Here is my saga:

function* getResults({ payload = 'user' }: ActionType<typeof actions.getResultsRequest>) {
  try {
    const { data } = yield call(api, `/results/${payload === 'user' ? 'me' : 'team'}`);
    const currentLanguage = getSavedState('user.currentLanguage')
    if (currentLanguage !== "ptBR") {
      const { results: statistics, adequate_protection, ...rest } = data
      const translatedProtection: ReturnType<typeof translateText> = yield call(translateText(data.adequate_protection, currentLanguage.replace(/[^a-z]/g, '')))
      yield put(actions.getResultsSuccess({ statistics, analysis: { ...rest, adequate_protection: translatedProtection } }));
    } else {
      const { results: statistics, ...rest } = data
      yield put(actions.getResultsSuccess({ statistics, analysis: { ...rest } }));
    }
  } catch (error) {
    yield put(actions.getResultsFailure({ status: true, message: 'Ocorreu um erro' }))
  }
}

And this is the translateText()

export const translateText = async (
  text: string | Array<string>,
  targetLanguage: string
) => {
  try {
    const [response] = await translate.translate(text, targetLanguage)
    let result: string | Array<string> = response

    if (Array.isArray(response)) {
      result = response.map((val: string, index) =>
        val !== '' ? val : text[index]
      )
    }
    return result
  } catch (error) {
    console.error('Error translate api =>', `${error}`)
    return text
  }
}

Solution

  • call takes a function and its args, but you're calling translateText and passing the resulting Promise into call. The error you are getting is likely a TypeError saying that the argument fn of type Promise is not callable.

    If you change:

    yield call(
      translateText(data.adequate_protection,
      currentLanguage.replace(/[^a-z]/g, ''))
    )
    

    to:

    yield call(
      translateText,
      data.adequate_protection,
      currentLanguage.replace(/[^a-z]/g, '')
    )
    

    then things should just work.