0

I have a generator function named addCart. And I have one generator function named watcher.

So I have console log('0') in my addCart. If I dispatch it now, why I see in my console two times 0?

0 0

and then I get two other payloads? (If I dispatch) why?

first payload:
payload{
    "el": {
        "id": 2,
        "article": "Computer",
        "price": 52.5
    },
    "cart2": []
}

second payload:
{
    "newCart": [
        {
            "id": 2,
            "article": "Computer",
            "price": 52.5
        }
    ],
    "newTotal": 52.5
}

action

export const addCart = payload => {
  return {
    type: 'ADD_TO_CART',
    payload
  }
};
import { all, take, put, call, takeEvery } from 'redux-saga/effects';
import { addCart} from './shopAction';
const total = el => {
  let total = 0;
  for(let i = 0; i < el.length; i++) {
    total += el[i].price
  }
  return total;
};

function* addToCart(payloads) {
  console.log('0');
  const newCart = [...payloads.payload.cart2, payloads.payload.el];
  const newTotal = total(newCart);
  yield put(addCart({newCart, newTotal}))
}

function* watcherCart() {
    yield takeEvery('ADD_TO_CART', addToCart);
}

export default function*() {
  yield all([watcherCart()]);
}

APP

...code

const handleAdd = (el, cart2) => {
    dispatch(addCart({el, cart2}));
};

  • In the app code, `addCart` is dispatching the action once, and then the call to `put(addCart(...))` in the generator dispatches it again. You would be getting an infinite loop but it looks like the `addToCart` saga will error the second time around based on the payload. – azundo Mar 10 '21 at 22:07
  • thanks for your answer, how can I fix it? – localdata001 Mar 10 '21 at 22:37
  • Depends what you're looking to do. Since you're not doing any async work in the saga in the example here I'm not sure why that code wouldn't just live in the reducer when handling the `ADD_TO_CART` action type. If you still want to kick off the saga but have a separate action dispatched for the reducer to handle then make a new action like `startAddToCart` that's dispatched from the app instead so you're not dispatching the same action twice. – azundo Mar 12 '21 at 06:11

0 Answers0