Search code examples
reactjsreact-hooksnext.jse-commercecloudinary

Update state of a Product while submitting a form React/NextJS


I'm trying to update my product object when the submit button is clicked but it doesn't update in that render.

const handleSubmit = async (e) => {
    e.preventDefault();
    const media = await imageUpload(files); // function  returns an array of links
    setProduct((prev) => ({ ...prev, images: media })); // Here where I want to update the images but it doesn't work
    await createProduct();
    setProduct(initialState); // reset to default
  };

I tried using an useEffect to detect when the button is clicked and then update the product but it doesn't work too.

Hope I made myself clear. Thank you in advance.


Solution

  • may be exctracting your CreateProduct function like so :

    const handleSubmit = async (e) => {
        e.preventDefault();
        const media = await imageUpload(files); // function  returns an array of links
        setProduct((prev) => ({ ...prev, images: media }));
      };
    
    useEffect(()=>{
     if(product){
      createProduct();
      setProduct(initialState);
     }
    },[product])