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!