I am trying to set an array in my local storage based on which version of an item is open. nearly this exact logic at the top level works perfectly fine upon page load. this function runs when a user clicks on an item to switch the version in the same page but in a nested component.
The console log of the currentlyOpenTabs object works just fine and shows the correct items expected in the array. But the local storage contains the state of the array with the 'id
' filtered out. for example, if my array is [1,2,3]
and i run loadVersion(4)
while on the page for version 1
, the localStorage shows [2,3]
, while the console log of currentlyOpenTabs
shows [2,3,4]
function loadVersion(id: string) { let getTabs = localStorage.getItem('openTabs') let currentlyOpenTabs: string[] = getTabs ? JSON.parse(getTabs) : [] if (currentlyOpenTabs.includes(id)) { const shouldUserContinue = confirm('warning message', ) if (!shouldUserContinue) { window.location.href = '/app/correctPathway' } } // these confirm that the ids are different console.log('id', id) console.log('storeid', $myStore.version_info.id) currentlyOpenTabs.push(id) currentlyOpenTabs = currentlyOpenTabs.filter( (item) => item !== $myStore.version_info.id, ) // this shows that currentlyOpenTabs has the correct items in it console.log(currentlyOpenTabs) // after this runs, localstorage openTabs is not the same as currentlyOpenTabs console logged localStorage.setItem('openTabs', JSON.stringify(currentlyOpenTabs)) const newUrl = new URL(window.location.href) newUrl.searchParams.set('versionId', id) goto(newUrl.toString(), { replaceState: true })}
I have tried changing the order of the logic to see if filtering before pushing new items made a difference. Honestly, I have tried many iterations of similar logic and finally got to this point where I realized localStorage just wasn't setting the right value.