Search code examples
node.jsreactjsdotenv

troubles using variable in .env files


I am working on a .env file for a tool I am building and I have the GET working it seems but the DELETE seems to be having trouble. The issue seems to be with the ${CollectorID} part in the function as it does not pull the ID, I am not seeing where I should have it. does it go in the .env or only in the function part. Below is my function for the onClick, Server.js and the .env, my main thing is that before I used the env I just had it be like http://localhost:5000/deleteCollector/${CollectorID} but that does not work with the env way of things I guess. This is the error I get when I click the delete button.

enter image description here

This is my function for my onClick event:

onDeleteClick = collectorID => {
    axios.delete(process.env.NODE_ENV === 'development' ? process.env.REACT_APP_DEV_DELETE`${collectorID}` : process.env.REACT_APP_PRO_DELETE`${collectorID}`);
    this.getCollectors();
    // window.location.reload(true);
};

My server.js looks like:

// Delete Collector
app.delete('/deleteCollector/:collectorID', (req, res) => {
    res.set('Access-Control-Allow-Origin', '*');
    sql.connect(config).then(pool => {
        return pool.request()
        .query(`DELETE FROM CollectorAssignment.tCollectorsTest
                WHERE collectorID = ${req.params.collectorID}`).then(result => {
            res.send(result.recordset)
        })
     })
})

.env file:

REACT_APP_DEV_DELETE = http://localhost:5000/deleteCollector/
REACT_APP_PRO_DELETE = https://support.pawneeleasing.com/PublishedCollectorAPI/api/Collector/

Solution

  • There's an issue with how you're concatenating the environment variable with collectorId.

    Instead of:

    process.env.REACT_APP_DEV_DELETE`${collectorID}`
    

    you want:

    `${process.env.REACT_APP_DEV_DELETE}${collectorID}`
    

    The unexpected error message ("x is not a function") is the result of the compiler seeing your backticks as a tagged template, rather than a simple template string.

    With that change, your onDeleteClick looks like this:

    onDeleteClick = collectorID => {
        axios.delete(process.env.NODE_ENV === 'development' 
           ? `${process.env.REACT_APP_DEV_DELETE}${collectorID}` 
           : `${process.env.REACT_APP_PRO_DELETE}${collectorID}`);
        this.getCollectors();
        // window.location.reload(true);
    };