4

私はreactjsを使用しているカートにアイテムを追加するための作業カートステートマシンを持っています。ページを更新すると、コンテキストが保持されません。ステート マシンを初めて使用するので、アプリで状態を保持したいと考えています。以下は私の cartMachine です。助けてください。ありがとうございます。

export const cartMachine = Machine(
  {
    id: "cart",
    initial: "idle",
    context: {
      ItemsInCart: [],
    },
    states: {
      idle: {
        on: {
          ADD: {
            target: "idle",
            actions: ["addProductsToCart"],
          },
        },
      },
    },
  },
  /* actions */
  {
    actions: {
      addProductToCart: assign((context, event) => {
        const { ItemsInCart } = context;
        const { item } = event;
        let checkIfProductInCart = ItemsInCart.find(({ id }) => id == item.id);
        let canAddToCart = checkIfProductInCart;

        if (!canAddToCart) {
          ItemsInCart.push({ ...item });
        }
      }),
    },
  }
);
4

3 に答える 3