Reset imported js file when back button is pressed

Viewed 66

I have question about how to reset the imported js file when user click on the back button and click forward button.

So for example

a.js file (where it will display the data) will import getData function data.js file. data.js file will send the data to the a.js file.

Example data for data.js file below

const data = [
  {
    id: "bee"
    bool: true
  },
  {
    id: "spider"
    bool: false
  }
]

const getData = () => {
   const tempData = data;
   // do the logic here and return
   return tempData;
}


export default {
  getData 
};

so lets say I change the data from the a.js file using the getData function after importing the data.js file. The data still holds the previous data. So if I change the id spider bool to true, it will still holds the value of true when user clicks on the back button and comeback to the page again with forward button.

I tried to do the useeffect to reset the data but that did not work... Is there a way to reset the data.js file?

1 Answers

You should send a clone of the data out by doing this:

const getData = () => {
   const tempData = [...data]; //creating a new array here breaks reference to the original
   // do the logic here and return
   return tempData;
}

and then create a setData function that will be in charge of updating the data within data.js if you ever want the changes to be reflected within that file.

Edit: create a restore state method that you call when you need to set the data back to the original:

const restoreState = () => {
   data.splice(0);
   data.push(...[
     {
       id: "bee"
       bool: true
     },
     {
       id: "spider"
       bool: false
     }
   ]);
}

or simply reassign the value of data if you choose to define data with let instead of const.

Related