1

I am trying to do a test task and I am prohibited from using libraries and plugins to work with DB, ORM.

I need to get data from a PostgreSQL table and display it in the React component, but I don't know how to fetch data from the node to react.

Here is how I get the data from the database:

const { Client } = require("pg");

const client = new Client({
  host: "localhost",
  user: "postgres",
  port: 5432,
  password: "postgres",
  database: "welbex-test",
});

client.connect();

client.query(`SELECT * from products`, (err, res) => {
  if (err) {
    console.log(err.message);
  } else {
    console.log(res.rows);
  }
  client.end;
});

Here is how I am trying to fetch data:

  useEffect(() => {
    const fetchProducts = async () => {
      setLoading(true);
      const res = await axios.get(
        "http://localhost:3000/src/Components/API/connect"
      );
      setProducts(res.data);
      setLoading(false);
    };
    fetchProducts();
  }, []);

1 Answer 1

3

You will need to setup server. Express is a popular server to export an api. Then change the endpoint to your server to fetch data. For example:

Your server:

const express = require('express')
const { Client } = require("pg");

const app = express()
const port = 3000

const client = new Client({
  host: "localhost",
  user: "postgres",
  port: 5432,
  password: "postgres",
  database: "welbex-test",
});


client.connect();

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

app.listen(port, () => {
  console.log(`Example app listening on port ${port}`)
})

Your component:

 useEffect(() => {
    const fetchProducts = async () => {
      setLoading(true);
      const res = await axios.get(
        "http://localhost:3000/products"
      );
      setProducts(res.data);
      setLoading(false);
    };
    fetchProducts();
  }, []);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.