Home > Mobile >  Actual value from useState
Actual value from useState

Time:06-11

I have my useState hook here:

const [countOfItemsInOrder, setCountOfItemsInOrder] = useState(0);

I call setState action in other component, and then I use it in object wich goes to redux. And I have a problem. My useState value in redux is previous.

Here is my function with setSate. Function calls on click:

const onPressAdd = () => {
    setStateAction(prevState => prevState   1);
    onAdd();
  };

I put setState action as a prop from other component. And then use object with state in my redux action:

const onAdd = () => {
    const totalPrice = servicesList.reduce(
      (sum, current) => sum   current.price,
      0,
    );
    const totalTime = servicesList.reduce(
      (sum, current) => sum   current.time,
      0,
    );

    const payload: OrderData = {
      id: 0,
      totalPrice,
      totalCount: countOfItemsInOrder,
      totalTime,
      name,
      services: servicesList,
    };

    dispatch({type: actions.order.addOrder.type, payload});
  };

So, for example, I click - on my screen value - 1, but in redux - 0. I click again, on screen - 2, in redux - 1. Can you help, how can I solve it?

CodePudding user response:

setState is asynchronous, so countOfItemsInOrder is not updated yet when you store it in Redux.

But, why do you have a state if you're storing this value in redux? Just create an action which will add 1 to totalCount, and retrieve countOfItemsInOrder (which is totalCount) directly from redux.

You don't need an internal state in your case

  • Related