I have a React project using redux-saga and I need to call 2 APIs to fetch all the data I need.
If I need to fetch all my products, I usually do this:
function* fetchProducts() {
const products = yield call(API.getProducts)
yield put({type: "UPDATE_PRODUCTS", products})
}
Now imagine that my product object has a brandId field that I can use to fetch brand data from another API.
I wanted to:
- Fetch all the products
- Loop the products and, for each product, load its brand information
- Update my
productsobject to include the brand information - Save that new
productsobject in my global state
I tried something like this:
function* fetchProducts() {
const products = yield call(API.getProducts)
const productsWithBrand = products.map((product) => {
const brand = yield call(API.getBrand, product.brandId)
return {
...product,
brandData: brand,
}
})
yield put({type: "UPDATE_PRODUCTS", productsWithBrand})
}
Which gives me the error:
Parsing error: Unexpected reserved word 'yield'
After reading this thread, I understood why the error is happening, but I can't figure out the proper syntax to achieve what I want.
Is there a common pattern to achieve what I need?