Jason Khalili
Jason Khalili

Reputation: 101

Send data to EJS after calling initial res.render?

I'm trying to pass a variable to EJS a second time in my code and am running into trouble. Here is my code:

axios.get(yearURL)
    .then(function (res) {
        let data = res.data.MRData.SeasonTable.Seasons;
        years = data.map(d => d.season);
        app.get('/', function (req, res) {
            res.render('index.ejs', { 
                years: years
            });
            app.post('/down', function(req, res) {
                let year = req.body;
                res.redirect('/');
                axios.get(`http://ergast.com/api/f1/${year.year}/drivers.json`)
                    .then(function (res) {
                        let data = res.data.MRData.DriverTable.Drivers;
                        drivers = data.map(d => `${d.givenName} ${d.familyName}`);
                    })
                    .catch(function (err) {
                        console.log(err);
                    })
                res.render('index.ejs', {
                    drivers: drivers,
                    years: years
                }); 

Whenever I run this however, I receive an error that I cannot set headers after they are sent to the client. I've also read elsewhere that apparently you can not call res.render twice. So my question is, how can I pass another set of data to EJS after I have already called res.render once before?

Upvotes: 0

Views: 62

Answers (1)

Josh Wulf
Josh Wulf

Reputation: 4877

Here it is as pseudocode. It's good to start your program with this level of logical structure, and then implement it:

  • Define ready = false, errored = false, and data = undefined variables.

  • Get the data from the remote API, in the then branch, set ready = true, assign result to data. In the error branch, set errored = true. Should we retry on error?

  • Define the / GET route.

    • If not ready, check errored. If not errored, we are still waiting for the data. In this case, do we wait for the call to resolve, or return something to the client to let them know?
    • If not ready, and errored, tell the client that there was an error.
    • If ready == true, then we have data to render a response to the client.
  • Define the /down route. It needs to take a year parameter, and we need to make an async call in the route handler to get the data.

    • Can we cache the data, so that subsequent calls for the same year return data that we fetched previously? If we can, use an object as a lookup dictionary. If the object has a key for that year, use the cached data to render the response. If not, make the call, and in the then branch, add the response to the cache object, and use the data to render the response.

Upvotes: 1

Related Questions