Click here to Skip to main content
15,881,173 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I am a beginner and Im trying to connect the dots and learn, my aim is to get the input values and post them to postgresql database as post request. My code so far.

What I have tried:

import { useState, useEffect } from "react";
import axios from "axios";
import Task from "./Task";
import "./App.scss";

function App() {
  //Value of Input
  const [val, setVal] = useState("");
  const [todos, setTodos] = useState([]);
  const [message, setMessage] = useState([]);

  const addTodos = async (e) => {
    if (val == "") return;
    e.preventDefault();

    const res = await axios
      .post("http://localhost:8000/message")
      .then((response) => console.log(response))
      .catch((error) => console.log(error));

    /** */
    setTodos([...todos, val]);
    setVal("");
    /** */
  };

  useEffect(() => {
    const fetchProducts = async () => {
      const res = await axios.get("http://localhost:8000/message");
      setMessage(res.data);
    };
    fetchProducts();
  }, []);

  const handleDelete = (id) => {
    setTodos(todos.filter((_, key) => key !== id));
  }; //#endregion

  return (
    <div>
      {/** On change values*/}
      
        <input
 onchange="{(e)" ==""> setVal(e.target.value)}
          value={val}
          type="text"
        />
        Add
      
      <ul>
        {todos.map((todo, key) => (
          <task todo="{todo}" key="{key}" mykey="{key}" handledelete="{handleDelete}">
        ))}
      </ul>
      {message.map((e) => (
        <div>{e.todo}</div>
      ))}
    </div>
  );
}

export default App;



//Server js 
const express = require("express");
const cors = require("cors");

const { Client } = require("pg");
const client = new Client({
  user: "jj",
  host: "localhost",
  database: "dbname",
  password: "rootuser",
  port: 5432,
});
client.connect();
const app = express();
app.use(cors());
app.use(express.json());

app.get("/message", async (req, res) => {
  const { rows } = await client.query(`SELECT * from todo`);
  res.send(rows);
});

app.listen(8000, () => {
  console.log(`Server is running on port 5174.`);
});


Can someone please help figure it via steps how i can manage to make the post request and make the connection with node js please ? Yesterday i managed successfully to get all the database entries and post them. I appreciate the help here and thank you.
Posted
Updated 31-Mar-23 2:10am
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900