#Update a product from a widget

3 messages · Page 1 of 1 (latest)

stiff forge
#

I have the following widget with an input and a save button, I want to update a custom field that adds to the product entity but I don't understand how to use the ProductServices.

This is my preview but it is not correct:

import ProductService from "src/services/product";
const ProductWidget = ({ product }: CurrentProduct) => {

  const handleUpdate = async () => {
    try {
      const newValue= 24;

      const productService: ProductService = new ProductService();
      await productService.update(product.id, { customField: newValue});
    } catch (error) {
      console.log("Error updating product discount");
      console.log(error);
    }
  };

  return (
    <Container>
  <Input
          className="mt-1"
          type="number"
          placeholder="0%"
          value={customField}
          onChange={handleInputChange}
        />
  <Button
            variant="primary"
            onClick={() => handleUpdate()}
            disabled={!hasChanged}
          >
            Update
          </Button>
    </Container>
  );
};

export const config: WidgetConfig = {
  zone: "product.details.after",
};
export default ProductWidget;
fierce ibex
#

I am not sure if you can use the product service in the Admin like that, you could also update the product using the medusa-react package. https://docs.medusajs.com/medusa-react/overview

Learn how to install Medusa React in a React storefront. Medusa React is a React library that provides a set of utilities and hooks for interactive with the Medusa backend.

#
import { useAdminUpdateProduct } from 'medusa-react'
...
const { mutateAsync: updateProduct } = useAdminUpdateProduct(<product_id_here>)

const handleUpdateProduct = async (data) => {
  await updateProduct({
     // your data here as key value pairs
  })
}