Duma Doniagara
Duma Doniagara

Reputation: 33

Yield call returning undefined

Anybody can help me what's wrong with my code. I trying to get data from API in sagas file like this. I've try to console.log the response.data in read function and I get the data (array). But when it assigned in variable (data) in generator function it has undefined.

// sagas.js

const PATH = 'product';

const read = async (path) => {
   await request.get(path)
      .then(response => {
         console.log('response from read :', response.data)
         return response.data;
      })
      .catch(err => { throw err })
}

function* loadProduct() {
   try {
      const data = yield call(read, PATH);
      yield put(actions.loadProductSuccess(data));
   }
   catch (error) {
      console.log('what's the error :', error)
      yield put(actions.loadProductFail());
   }
}


export default function* rootSaga() {
   yield all([
      takeEvery('LOAD_PRODUCT', loadProduct)
   ]);
} 

Upvotes: 1

Views: 1663

Answers (2)

Duma Doniagara
Duma Doniagara

Reputation: 33

Thanks a lot, I got my problem. I forgot about the curly brace, I change my code like this:

const PATH = 'product';

const read = async (path) => 
   await request.get(path)
      .then(response => {
         console.log('response from read :', response.data)
         return response.data;
      })
      .catch(err => { throw err })

...

it works properly!

Upvotes: 1

Lin Du
Lin Du

Reputation: 102672

You need to return await request.get(path), then you will get response.data in your saga functions.

Upvotes: 0

Related Questions