0

I am trying to make a PUT request to update a user's profile using Axios in a next.js application. The request includes a multipart/form-data payload to send user information and an optional profile picture. However, I am encountering an error and need help resolving it.

Here is the code I am using:

import React, { useState } from "react";
import axios from "axios";

const EditAccount = () => {

State variables

const [selectedImage, setSelectedImage] = useState<string | null>(null);
  const [username, setUsername] = useState("");
  const [name, setName] = useState("");
  const [password, setPassword] = useState("");

Get the token from localStorage

const token = localStorage.getItem("token");

Create a new FormData object

  const handleSaveChanges = () => {
    const formData = new FormData();
    formData.append("username", username);
    formData.append("name", name);
    formData.append("password", password);
    if (selectedImage) {
      formData.append("profilePicture", selectedImage);
    }

Make the PUT request using Axios

    axios
      .put("http://192.168.0.72:4000/api/updateprofile", formData, {
        headers: {
          "Content-Type": "multipart/form-data",
          Authorization: `Bearer ${token}`,
        },
      })
      .then((res) => {
        console.log(res.data);
      })
      .catch((err) => {
        console.error(err);
      });
  };

  console.log(token);
};

HTML

 return (
    <div className="flex flex-col items-center justify-center h screen">
      <h1 className="text-3xl font-bold mb-4">Edit Profile</h1>

      <div className="rounded-lg p-4 mb-4">
        
        <div className="w-24 h-24 bg-gray-900 rounded-full mx-auto mt-4 mb-2">
          {selectedImage ? (
            <img
              src={selectedImage}
              alt="Profile"
              className="w-full h-full rounded-full"
            />
          ) : null}
        </div>
      
      <div className="text-sm mb-8"></div>
        <label
          htmlFor="profilePicture"
          className="bg-green-900 hover:bg-green-600 text-white font-semibold py-2 px-4 rounded cursor-pointer"
        >
          Change Profile Picture
          <input
            type="file"
            id="profilePicture"
            className="hidden"
            accept="image/*"
            onChange={handleProfilePictureChange}
          />
        </label>
      </div>

      <form className="w-full max-w-sm">
        
        <div className="mb-4">
          <label
            htmlFor="username"
            className="block text-gray-700 font-bold mb-2"
          >
            Username
          </label>
          <input
            type="text"
            id="username"
            className="border border-gray-300 rounded px-4 py-2 w-full"
            placeholder="Change your username"
            value={username}
            onChange={(e) => setUsername(e.target.value)}
          />
        </div>

        <div className="mb-4">
          <label htmlFor="name" className="block text-gray-700 font-bold mb-2">
            Name
          </label>
          <input
            type="text"
            id="name"
            className="border border-gray-300 rounded px-4 py-2 w-full"
            placeholder="Change your name"
            value={name}
            onChange={(e) => setName(e.target.value)}
          />
        </div>

        <div className="mb-4">
          <label
            htmlFor="password"
            className="block text-gray-700 font-bold mb-2"
          >
            Password
          </label>
          <input
            type="password"
            id="password"
            className="border border-gray-300 rounded px-4 py-2 w-full"
            placeholder="Change your password"
            value={password}
            onChange={(e) => setPassword(e.target.value)}
          />
        </div>

        <div className="flex justify-center">
          <button
            className="bg-green-900 hover:bg-green-600 text-white font-semibold py-2 px-4 rounded"
            onClick={handleSaveChanges}
          >
            Save Changes
          </button>
        </div>
      
      </form>
    </div>
  ); 

The error that I'm encountering is an AxiosError with the name ECONNABORTED. The error occurs when making an axios.put request, and the request is being aborted.

I have ensured that the token is present and correctly retrieved from localStorage. I have also verified that the URL and endpoint are correct.

Can someone please help me identify and resolve the issue with this Axios request? Thank you in advance!

bronubora
  • 1
  • 3
  • Remove the content-type header, it is incomplete and redundant – Phil May 31 '23 at 09:12
  • You typically get this error when you forget to prevent the default action for a form submit event. Without seeing your HTML or what triggers `handleSaveChanges()`, I could only guess at what the solution would be – Phil May 31 '23 at 09:15
  • 1
    Does this answer your question? [Stop form refreshing page on submit](https://stackoverflow.com/questions/19454310/stop-form-refreshing-page-on-submit) – Phil May 31 '23 at 09:16
  • @Phil I added the html to the question. – bronubora May 31 '23 at 09:25
  • As expected. Add `type="button"` to your button and accept the duplicate – Phil May 31 '23 at 10:10

0 Answers0