How to make Frontend ready for PUT ?

How to make Frontend ready for PUT
How to make Frontend ready for PUT

To make your frontend ready for PUT (update) requests, you’ll need to add the ability to:

  1. Select a product for editing.
  2. Pre-fill the form with the product’s existing data.
  3. Send a PUT request to update the product on the backend.
  4. Update the product in the frontend state after a successful update.

Setup the NextJS Application

Install everything

npx create-next-app@latest my-next-app

npm install axios

Create the UI ( Form ) + Axios PUT Query

Make the form yourself

Make sure form’s enctype is set to "multipart/form-data".

<form onSubmit={HandleSubmit} className="mb-10" enctype="multipart/form-data">

    //........................
    //........................
    //........................
    //........................

  <button style={styles.submitbtn} type="submit">Update Product</button>

</form>

NOW PUT REQUEST IN HandleSubmit

const HandleSubmit = async (e) => {
  e.preventDefault(); // Prevent page reload

  try {
    const formData = new FormData(); // Create FormData object to handle files and inputs

    // Append image files to FormData (only if available)
    Object.keys(images).forEach((key) => {
      if (images[key]) {
        formData.append(key, images[key]); // e.g., 'displayImage', 'firstImage'
      }
    });

    // Append input fields to FormData
    Object.keys(inputs).forEach((key) => {
      formData.append(key, inputs[key]); // e.g., 'slug', 'title', 'category'
    });

    // Send PUT request using Axios
    const response = await axios.put(
      `http://localhost:8000/api/product/${params.id}`, // PUT endpoint
      formData,
      {
        headers: {
          'Content-Type': 'multipart/form-data', // Ensure correct headers for file uploads
        },
      }
    );

    console.log('Product updated successfully:', response.data);
    alert('Product updated successfully!'); // Optional user feedback
  } catch (error) {
    console.error('Error updating product:', error);
    alert('Failed to update the product. Please try again.'); // Optional error feedback
  }
};