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() {
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));
};
return (
<div>
{}
<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;
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.