redux saga function is called twice

345 Views Asked by At

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}));
};

0

There are 0 best solutions below