0

I have a function in JS that fetches some data and then uses it in a function to load post:

function getPosts(){
    fetch(`/load/${offset}/${sort}/1`)
        .then(response => response.json())
        .then(results => loadPostsIntoSection(results));
}
exports.getPosts = getPosts();

I want to use it right after I render the page so some results will already be there before needing to load more. Kinda like this:

const ui = require('../public/js/ui.js');

router.get('/', authController.isLoggedIn, (req, res, next) => {
  
  res.render('index');
  ui.getPosts();

});

But I get an error:

window.onclick = function(event) {
^

ReferenceError: window is not defined

How do I make the function start in the browser so I don't get nodeJS error for fetch and window not existing?

kaPa
  • 87
  • 10
  • You can either run the function in the browser or use a library that implements fetch in node... Not sure what you're asking – Dominik Aug 15 '21 at 22:10
  • Check https://stackoverflow.com/questions/48433783/referenceerror-fetch-is-not-defined Probably not installed fetch module – nillo Aug 15 '21 at 22:27

1 Answers1

0

The only solution I found was to implement the same fetch on the client-side JS right after loading.

kaPa
  • 87
  • 10