0

I am trying to reload the latest data from a database when the browser back button is clicked.

However, even though the following code runs, and the data has already been updated in the database, the page still loads the old data.

 window.addEventListener("popstate", getItemsFromDB) // works on first page load and when back button is clicked
 ...

    function getItemsFromDB() {
     fetch('http://localhost:4000')
        .then(res => {
            res.json().then(data => {
            console.log('RESP', data) // data is old here on navigating back to index page
     })
   ...

I have buttons that upvote individual items in the list that work fine, ie. a button is clicked for an upvote, the item is updated in the DB and the new data for the item is added on the page.

Now, when I navigate away from the page and then back using the back button, the getItemsFromDB() function gets called but doesn't the fetch() doesn't execute. Hence, the data reverts to the previous state.

Only a manual refresh of the page will load the latest data. Can anyone tell me what's going wrong here?

Also, I would like to do this with plain vanilla JS instead of using jQuery or a framework.

Thanks!

mikeym
  • 5,705
  • 8
  • 42
  • 62
  • Would forcing a full page (automatic) reload work for you? – GrafiCode Sep 14 '22 at 20:08
  • I mean, if you do `window.addEventListener("popstate", location.reload())` does the page reload when hitting "back"? – GrafiCode Sep 14 '22 at 20:13
  • 1
    if `getItemsFromDB()` get called then the `fetch()` would also be called. maybe it's cached so you don't get latest data. – apple apple Sep 14 '22 at 20:18
  • @appleapple that's exactly the reason – GrafiCode Sep 14 '22 at 20:19
  • **Cache busting** is the best solution: https://stackoverflow.com/a/49439164/5334486 – GrafiCode Sep 14 '22 at 20:19
  • @GrafiCode I didn't say for sure simply because OP say it's not called. maybe OP take it wrong or maybe it's actually not called. – apple apple Sep 14 '22 at 20:20
  • @appleapple I was checking the linked answer before your comment, I'm pretty confident that's the underlying problem for OP (linked answer belongs to a question almost identical to this) – GrafiCode Sep 14 '22 at 20:23
  • @GrafiCode just to clear up any confusion, the `getItemsFromDB()` function IS called both on the initial page load AND on the back button click. The problem is the `fetch()` appears to be called but does not return the latest data. I thought it might be a caching issue. Thanks for the response. – mikeym Sep 14 '22 at 20:46
  • ok then, try cache busting your fetch request, `fetch('http://localhost:4000/?r=' + randomCharacters)` it should always return fresh data – GrafiCode Sep 14 '22 at 20:55

0 Answers0