How to retrieve the value of a yield function call?

299 Views Asked by At

I am working on a project which began last year, and the developers are not with me. They wrote this code :

import { put, takeLatest, all, call } from 'redux-saga/effects';
import { getUserByUsernameService } from '../../services/userServices';
import 'regenerator-runtime/runtime';

function* fetchUser() {
  const response = yield call(getUserByUsernameService);
  yield put({ type: 'FETCHED_USER', payload: response.data.user });
}

function* actionWatcher() {
  yield takeLatest('FETCHING_USER', fetchUser);
}
export default function* rootSaga() {
  yield all([actionWatcher()]);
}

Code of getUserByUsernameService :

import {
  makeGetRequest,
  makePostRequest,
  makePutRequest,
  makeDeleteRequest,
} from '../utils/reqUtils';

export const getUserByUsernameService = (params) => {
  let headers = {
    "Access-Control-Allow-Origin": "*"
  };
  makeGetRequest('/user', params, headers);
}

Code of makeGetRequest :

import axios from 'axios';
export const makeGetRequest = (endpoint, params = {}, headers) => {
  const options = {
    method: 'GET',
    headers: { ...headers },
    params: params,
    url: endpoint,
  };

  return axiosInstance(options)
    .then((resp) => resp.data)
    .catch((e) => {
      console.log(e);
      throw e;
    });
};

At runtime I get Cannot read property 'data' of undefined corresponding to the code

yield put({ type: 'FETCHED_USER', payload: response.data.user });

So what is wrong ?

2

There are 2 best solutions below

2
On

The generator yield returns an object that you can iterate using next method.

I think you should use response.next().valute.data.user. I think also as you consume the generator in fetchUser you should not yield the result of the call API method.

function* fetchUser() {
  const response = call(getUserByUsernameService);
  yield put({ type: 'FETCHED_USER', payload: response.next().value.data.user });
}
0
On

This is a simple typo — you forgot to return something from your getUserByUsernameService function! You are calling makeGetRequest but not returning the response. You want

return makeGetRequest('/user', params, headers);