Search code examples
reactjsreduxsaga

class component is not defined in Saga-request


I have an Api-request in Saga React. Request function is placed in another folder. I want to call it in Saga file, but get a mistake, that ProductService is not defined. Can it be connected with Saga? The way is right. The function worked when it was on Saga-page but stopped when I transferred it in another folder.

import ProductService from "../services/productService";

function* fetchProductById(productsInList) {      
  ProductService = new ProductService();
  const myListProducts = productsInList.payload.activity.map((item) =>
   //it's request to another file 
  ProductService.getProductByKey(item)
  );
  const res = yield call(() => Promise.all(myListProducts));
  yield put(productsInMyList(res));
}

//another folder

  export default class ProductService {
        async getProductByKey(key) {    
            const data = new URLSearchParams();
            data.append("key", key);
            const res = await this.getResource(`?${data}`);    
            return await res.json();
          } 
        }

Solution

  • I think it is because of your naming. you have both the imported class and its instance in the same name ProductService. You can change your code as below

    import {call, all} from 'redux-saga/effects';
    import ProductService from "../services/productService";
    
    function* fetchProductById(productsInList) {
      const productServiceObj = new ProductService();
      const myListProducts = productsInList.payload.activity.map((item) =>
        call(productServiceObj.getProductByKey, item)
      );
      const res = yield all(myListProducts);
      yield put(productsInMyList(res));
    }