Home > OS >  How do I use an external API in my React project?
How do I use an external API in my React project?

Time:03-30

Apologies for the duplicate question I'm sure this has been asked many times before.

I'm using React, Express, CORS, node, postgres. I would like to use the following api to retrieve live price for metals:

https://metals-api.com/

I can use my API with my test app, I would also like in addition to use the API from above

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

//middleware
app.use(cors());
app.use(express.json());

//ROUTES

And here is one of my example routes:

//Add entry to contact table
app.post("/contact", async (req, res) => {
    try {

        const {scontact_name} = req.body;
        const newContactName = await pool.query(
            'INSERT INTO supplier_contacts (scontact_name) VALUES ($1)', [scontact_name]);

        res.json(newContactName);

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

So to clarify there is my local API used to communicate with the postgres db. In addition I would like to use the api linked above to get some price information, help is much appreciated!

CodePudding user response:

Javascript has a build-in fetch method (see here) You can also use any 3rd party libary, for example axios

You can easily call their methods in a async function and then do what ever you whish with the response.

  • Related