0

I have api weather data being passed to my ejs template. I have a conditional statement to check to see if any api data exists. Regardless, I always get the following error:

Cannot read property 'temps' of undefined

The conditional statement if within a script tag.

<script>


    if ( JSON.parse('<%-locals.forecast.temps[0]%>') != undefined){

    console.log('there is data');


    var height = 500;
    var width = 800;
    var margins = {
        left: 40,
        top: 40,
        right: 40,
        bottom: 40
    }



            var barData = [
                {strength:JSON.parse('<%-locals.forecast.temps[0]%>')},
                {strength:JSON.parse('<%-locals.forecast.temps[1]%>')},
                {strength:JSON.parse('<%-locals.forecast.temps[2]%>')},
                {strength:JSON.parse('<%-locals.forecast.temps[3]%>')},
                {strength:JSON.parse('<%-locals.forecast.temps[4]%>')},
                {strength:JSON.parse('<%-locals.forecast.temps[5]%>')},
                {strength:JSON.parse('<%-locals.forecast.temps[6]%>')},
                {strength:JSON.parse('<%-locals.forecast.temps[7]%>')},
                {strength:JSON.parse('<%-locals.forecast.temps[8]%>')},
                {strength:JSON.parse('<%-locals.forecast.temps[9]%>')},
            ]
lcolsant
  • 1
  • 3

1 Answers1

0

It turns out that the script tag runs client side after the server renders the ejs template. So even though locals.forecast.temps[0] would work outside of the script tag it won't work within. I ended up creating a separate variable that stores the server side values when the template engine runs and then passes that variable to the script client side so that it is accessible without needing to go back to the server.

Outside of script tag within ejs template....

<% var forecast_data = locals.forecast.temps  %>

Inside of script tag...

var get_forecast_data = '<%= forecast_data %>'

This post was helpful: Can a js script get a variable written in a EJS context/page within the same file

lcolsant
  • 1
  • 3