Unable to Populate Database Records When Sending PUT Request in Next.js Application

8 Views Asked by At

I'm working on a Next.js application where I'm trying to implement functionality to save listings to a user's favorites. I have set up a PUT request to an API endpoint (/api/listing/favorites) to update the user's favorite listings in the database.

However, when I send the PUT request with the necessary data, the database records are not being populated with the updated favorite listings. I have verified that the API endpoint is being called, and I'm not receiving any errors in the response.

const [saveProp, setSaveProp] = useState<SavedListing[]>([]);

  const sendFavListing = async (updatedSaveProp: SavedListing[]) => {
    try {
      const response = await fetch(
        `${process.env.NEXT_PUBLIC_API_BASE_URL}/api/listing/favorites`,
        {
          method: "PUT",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify(updatedSaveProp), // Pass the array of updated saved listings
        }
      );

      if (response.ok) {
        const saveData: SavedListing[] = await response.json();
        // Update state with the received data
        setSaveProp(saveData);
        console.log("Property:", saveData);
      } else {
        console.error("Failed to update favorites");
        // Handle non-OK response
      }
    } catch (error) {
      console.error("Error updating favorites", error);
      // Handle error
    }
  };

What's weird about this is when I provided a map over a button to be used for individual properties it disappears.

     {saveProp.map((saveList) => (
                  <button
                    key={saveList.listingId} // Ensure to provide a unique key when mapping over an array
                    onClick={() => toggleSavedListing(saveList)} // Pass both index and saveList
                    className="w-20 h-10 font-agrandir tracking-wide flex justify-evenly items-center p-2"
                  >
                    <span>
                      {saveList.email ? ( // Assuming saveList has a property 'saved' indicating if it's saved
                        <FontAwesomeIcon
                          icon={faCheck}
                          size="lg"
                          className="w-4 h-4 text-pine px-2"
                        />
                      ) : (
                        <FontAwesomeIcon
                          icon={faPlus}
                          size="lg"
                          className="w-4 h-4 text-black px-2"
                        />
                      )}
                    </span>
                    <span>{saveList.email ? "Saved" : "Save"}</span>
                  </button>
                ))}
0

There are 0 best solutions below