persist search filters across multiple routes vue 3 (comp api)

Viewed 211

I'm trying to persist search filters across different routes without the use of Vuex. I'm using the composition api in vue 3. I looked into using localStorage with onBeforeRouteLeave and also watchEffect.

Below is the relevant code for adding/removing filters

const activeFilters = ref([]);

function addFilter() {
  activeFilters.value.push({
    value: filtered.value,
  });
  filtered.value = "";
}

function removeFilter(idx) {
  activeFilters.value.splice(idx, 1);
}

I tried the following, but doesn't seem to work:

 onMounted(() => {
   if (localStorage.filters) {
     activeFilters.value = JSON.parse(localStorage.filters);
   }
 });
onBeforeRouteLeave((to, from) => {
   localStorage.filters = JSON.stringify(activeFilters.value);
 });

Edit:

I've made some changes that looks like it gets me closer to the solution, but the behavior is inconsistent. On the route change, sometimes the filter is persisted, sometimes it's not.

const activeFilters = ref(JSON.parse(localStorage.filters) || []);
watch(
  () => activeFilters.value,
  (settings) => {
    localStorage.filters = JSON.stringify(settings);
  },
  { deep: true }
);
1 Answers

The issue wasn't actually with the localStorage code. I forgot I had made some changes to the router-view tag and forget to remove them. For any of those that need help, here's the code I ended up with to persist the search filters across multiple routes.

const activeFilters = ref([]);

onMounted(() => {
  console.log(localStorage.filters);
  if (localStorage.filters) {
    activeFilters.value = JSON.parse(localStorage.filters);
  }
});

watch(
  () => activeFilters.value,
  (settings) => {
    localStorage.filters = JSON.stringify(settings);
  },
  { deep: true }
);
Related