{ error: unable to update backend column due to invalid input syntax for integer: "undefined"}

Using a combination of postgresql database, expressJs, and react, I am currently looking to update a specific column called inCart within my database. I have implemented a fetch function that utilizes a PUT method and is triggered by an onClick event. However, I am unsure how to modify the value in the database once the onClick event occurs. Below is the code snippet I am currently working with:

import React, { Component, useEffect, useState } from "react";
import {
  BrowserRouter as Router,
  Switch,
  Route,
  Link,
  useParams
} from "react-router-dom";
import "./ProductPageBody.scss";

const ProductPageBody = () => {
  const [products, setProducts] = useState([]);

  let { shirtName } = useParams();
  let shirt = products.filter(product => product.name === shirtName);

  const [inCart, setInCart] = useState(shirt.inCart);
  
  useEffect(() => {
    getProducts();
  }, []);

  const getProducts = async () => {
    try {
      const response = await fetch("http://localhost:5000/carts/");
      const jsonData = await response.json();

      setProducts(jsonData);
    } catch (err) {
      console.error(err.message);
    }
  };

  //Update inCart Function
  const updateInCart = async e => {
    e.preventDefault();
    try {
      {e => setInCart("true")};
      const body = { inCart };
      const response = await fetch(`http://localhost:5000/carts/${shirt.id}`, {
        method: "PUT",
        headers: {"Content-Type": "application/json"},
        body: JSON.stringify(body)
      })
      console.log(response);

    } catch (err) 
    {
      console.error(err.message)  
    }
  } 

  return (
    <div
      className="container-fluid mt-5 m-auto p-0"
      style={{ paddingTop: "74px" }}
    >
      {shirt.map((shirt) => (
        <div className="row" key={shirt.id}>
          <div className="col-md-12 col-lg-4 ml-auto">
            <img
              src={shirt.image}
              alt={shirt.name}
              className="img-responsive w-100"
            />
          </div>

          <div className="col-md-12 col-lg-3 h-25 mt-5 mr-auto">
            <h1>{shirt.name}</h1>
            <div className="Pricing mt-3 mb-5">
              <h3 className="text-danger float-left mr-4">
                ${shirt.price}
              </h3>
              <select className="buttons form-control float-left mb-2">
                <option>Small</option>
                <option>Medium</option>
                <option>Large</option>
              </select>
              <button
                type="button"
                className="buttons btn btn-danger mt-2 h-auto w-100"
                onClick={e => updateInCart(e)}
              >
                ADD TO CART
              </button>
            </div>

            <p>{shirt.description}</p>
            <ul className="mt-2">
              <li>{"95% polyester, 5% elastane (fabric composition may vary by 1%)"}</li>
              <li>{"95% polyester, 5% elastane (fabric composition may vary by 1%)"}</li>
            </ul>
          </div>
        </div>
        ))}
    </div>
  );
};

export default ProductPageBody;

I am making progress but would appreciate any assistance!

Edit: As requested, here is the Express backend code:

const express = require("express");
const app = express();
const cors = require("cors");
const pool = require("./db");
const PORT = 5000;


//
//Middleware
//

app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: false }));


//Listens for server to start
app.listen(PORT, () => {
    console.log("Express Server has started on port", { PORT });
  });


//
//Routes
//

//Add a product
app.post("/carts", async (req, res) => {
  try {
    const { name } = req.body;
    const { category } = req.body;
    const { price } = req.body;
    const { description } = req.body;
    const { image } = req.body;
    const newProduct = await pool.query(
      "INSERT INTO products(name, category, price, description, image) VALUES($1, $2, $3, $4, $5) RETURNING *",
      [name, category, price, description, image]
    );
    res.json(newProduct.rows[0]);
  } catch (err) {
    console.error(err);
  }
});

//Show all products
app.get("/carts", async (req, res) => {
  try {
    const allProducts = await pool.query("SELECT * FROM products");
    res.json(allProducts.rows);
  } catch (err) {
    console.log(err);
  }
});

//Show specific product
app.get("/carts/:id", async (req, res) => {
  try {
    const { id } = req.params;
    const product = await pool.query("SELECT * FROM products WHERE id = $1", [
      id,
    ]);
    res.json(product.rows[0]);
  } catch (err) {
    console.log(err);
  }
});

//Update a product
app.put("/carts/:id", async (req, res) => {
  try {
    const { id } = req.params;
    const { name } = req.body;
    const { category } = req.body;
    const { price } = req.body;
    const { description } = req.body;
    const { image } = req.body;
    const { in_cart } = req.body;
    const updateProduct = await pool.query(
      "UPDATE products SET name = $1, category = $2, price = $3, description = $4, image = $5, in_cart = $6 WHERE id = $7",
      [name, category, price, description, image, in_cart, id]
    );
    res.json("Successfully Updated");
  } catch (err) {
    console.log(err);
  }
});

//Delete a product
app.delete("/carts/:id", async (req, res) => {
  try {
    const { id } = req.params;
    const deleteProduct = await pool.query(
      "DELETE FROM products WHERE id = $1",
      [id]
    );
    res.json("Successfully Deleted");
  } catch (err) {
    console.log(err);
  }
});

Answer №1

If you need to update a single column at once, there are multiple approaches you can take. One option is to create a new API specifically for updating individual columns, or you could modify your existing API to handle updates based on the values provided.

Here's an example of a simple API that can update any column in the Products table. To do this, you'll need to provide data in the following format:

URL =

http://localhost:5000/carts/${shirt.id}/single

{
   "key" : "in_cart",
   "value" : true
}
app.put("/carts/:id/single", async (req, res) => {
  try {
    const { id } = req.params;
    const { key } = req.body;
    const { value } = req.body;
    
    const updateString = `${key} = ${value}`;  

    const updateProduct = await pool.query(
      "UPDATE products SET "+updateString+" WHERE id = $1",
      [id]
    );
    res.json("Successfully Updated");
  } catch (err) {
    console.log(err);
  }
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to apply conditional hovering in styled components?

Is there a way to customize the hover effect of a component based on specific props? I want the background to change when hovering over it if certain props are set, but do nothing if different props are specified. export const Container = styled.div` ...

Having trouble with string matching in JavaScript?

My attempts to verify my Ajax response with a string have consistently resulted in a fail case being printed. Below is the section of code relating to my ajax request: var username = document.getElementById("name").value; var password = document.getEle ...

Unpacking Objects in JavaScript and TypeScript: The Power of Destructuring

I have a variable called props. The type includes VariantTheme, VariantSize, VariantGradient, and React.DOMAttributes<HTMLOrSVGElement> Now I need to create another variable, let's name it htmlProps. I want to transfer the values from props to ...

Show just a trio of pagination figures from the overall collection in Javascript

I have been working on implementing pagination numbers in JavaScript. While I have managed to achieve pagination and display all the numbers, I am looking to show only three numbers out of all the available numbers. Here's what I have accomplished so ...

Is it possible to use a Wcf polling duplex service with a client that is not using Silverlight?

I've been developing an online TicTacToe game and I'm utilizing a WCF polling duplex service to make it work. However, after dedicating a whole week to research, it seems that this service is only possible for Silverlight clients. If anyone is a ...

Error: Authentication error. fatal: Unable to access the remote repository." encountered while executing the command "yarn install

Today, while developing a web application, I encountered an issue with the "yarn install" command. Upon running "yarn install", the console displayed an error message: "Host key verification failed. fatal: Could not read from remote repository." I attemp ...

Exploring the challenges of implementing the Lob Node API wrapper within a MeteorJs project due to conflicts with the 'fs' module

I recently updated to the latest version of Meteor (1.13) which now supports NPM. I decided to add the Lob.com NPM to my project and started working on a letter function. However, I encountered the following error: Uncaught TypeError: fs.readdirSync is ...

Nested Ajax request fails and triggers a full page reload

My goal is to search for product information and images using a product code input on index.php. The query runs in open_first.php via an ajax post request, which works perfectly. open_first.php displays images that can be selected by clicking on them. How ...

Generate a fresh array from the existing array and extract various properties to form a child object or sub-array

I am dealing with an array of Responses that contain multiple IDs along with different question answers. Responses = [0:{Id : 1,Name : John, QuestionId :1,Answer :8}, 1:{Id : 1,Name : John, QuestionId :2,Answer :9}, 2:{Id : 1,Name : John, QuestionId :3,An ...

Implementing event handling for external modules using on method in Node.js

I have been utilizing the request module (available at https://www.npmjs.com/package/request) for executing a series of http requests in my application. However, I am currently facing an issue while attempting to integrate a logging feature into it. I am s ...

Tips for resolving the issue of missing metadata for open graph and Twitter cards in a Next.js project

Having trouble with error messages while running the build version in Next.js. I've added meta tags to the layout, but the issue persists. As a newcomer to Next.js, I'm looking for guidance on how to fix this problem. Any help or advice on troubl ...

Clear all CSS styles applied to a targeted division

My website built on Wordpress links to several CSS files. One specific div has its own unique style that is separate from the main Wordpress styles. Unfortunately, the Wordpress CSS ends up interfering with my custom div's layout. Is there a way in HT ...

Save the webpage source code to a file using JavaScript and Grunt

I am facing an issue and need assistance with my project. I have developed an app using GruntJs and now I need to download the source code of a webpage using GruntJs. For instance, let's assume I have a webpage at: example.com/index.html. What I wou ...

Keep your data safe and protected within a Node CLI application

Currently developing a NodeJS command-line application that interacts with an API to provide data to users. To access the public API, users need an API token. The CLI will be globally installed on users' machines using npm i -g super-cool-api-cli. Up ...

Updating nested arrays within objects in MongoDB

I'm currently facing an issue while attempting to update a value within a nested array. Here's what my object looks like: User.findByIdAndUpdate({ _id : userId, 'vehicle._id' : vehicleId },{ $push : { reg_number : reg_number, ...

Creating custom shaders for YouTube videos within a Three.js userscript

I want to add a shader effect to YouTube videos. My current approach involves using Three.js to implement a shader on a video. Specifically, I am trying to adapt this example of applying a shader to a video (code available here) into a Tampermonkey usersc ...

Tips for selectively loading JS resources on individual pages in Grails version 2.2.4

Is there a way to selectively load certain JS resources on specific pages in Grails 2.2.4? Currently, all JS files are being loaded on every page, even if they are not needed. The configuration in my ApplicationResources file is as follows: modules = { ...

Determine whether all elements in the array are false using Array.every()

Below is an example of an array: myArray = {firstValue: false, secondValue: false, thirdValue: true, forthValue: false}; The goal is to determine if every value in the array is false. If that condition is met, then perform a specific action. For instance ...

Rows on bootstrap do not have columns in alignment

Something peculiar is happening to me. I have the following snippet of HTML code, but the issue lies in the fact that the panelPrincipal begins hidden with the following JavaScript code: var panelPrincipal = document.getElementById('panelPrincipal&apo ...

JavaScript property counterparts

Recently, I've been working on creating alias's for a specific property in my code. var default_commands = {} default_commands['foo'] = "bar"; My goal is to create multiple aliases for the key 'foo' in the object. For examp ...