Node Axios wont render api data unless clicked twice

Viewed 63

I'm trying to get api data using axios (This is working) and rendering at the same time when I press the anchor tag.

Unfortunately, i have to click it two times, once get the api data (I can see it in console), and I have to pressed again to render the data. I can not figure out how to fix it.

const getCrypto =  async () => {
    try {
        const response = await axios.get(url)
        if(response){
        crypto =  response.data;
        console.log(crypto)
        };
    } catch (err){
        console.log(err)
    }
}

app.get('/', function (req,res){
    money = GBP;
    getCrypto();
   res.render('index.ejs', {cryptos:crypto, money:money}); 
})
1 Answers

Basically: getCrypto() call should be awaited (and the handler function be made async to allow for the use of the await keyword).

The reason it works in 2 clicks is that the variable crypto seems to be a global one - which is kind of dangerous practice.

Here is a more readable way of coding this:

const getCrypto = async () => {
    try {
        const response = await axios.get(url);
        if (response) {
            // this goes into a local (const-declared) variable...
            const crypto = response.data;
            console.log(crypto);
            // ...and return it
            return crypto;
        };
    } catch (err) {
        console.log(err);
    }
};

app.get('/', async (req, res) => {
    money = GBP;
    // await the result and put it in a local (const-declared) variable...
    const crypto = await getCrypto();
    // ...and push it to your renderer
    res.render('index.ejs', {cryptos: crypto, money: money}); 
});

However this is only your current problem, this doesn't account for error management - but I assume you'll eventually get there. ;)

Related