How can you stop VueUse useStorage from filling localStorage again after clearing it?

Using Vue 3 in combination with VueUse's useStorage to sync reactive state with localStorage has presented a challenge for me. Whenever I programmatically clear localStorage during user logout processes, it seems to automatically refill with previous values. Here’s my current approach to handling the logout scenario:

import { useStorage, nextTick } from '@vueuse/core';

const userSettings = useStorage('user-settings', {});

async function logoutAndClear() {
  // Reset user settings before clearing localStorage
  userSettings.value = {}; 

  await nextTick(); // Ensuring Vue's reactivity system updates the state

  localStorage.clear(); // Attempting to clear all localStorage items
}

Despite these efforts, old user-settings values quickly repopulate in localStorage right after the clear() operation. My suspicion is that VueUse's reactivity system detects changes and writes back to localStorage.

How can I effectively clear localStorage without triggering an immediate refill by VueUse's useStorage?

Answer №1

As stated in the documentation, setting a null value to the state will remove it from storage completely.

Instead of resetting the local storage value to an empty object, make sure to set it to null.

const userSettings = useStorage('user-settings', {});

function logoutAndClear() {
  userSettings.value = null; 
}

If you don't want the default value {} to populate after a page refresh, initialize it as null by default.

const userSettings = useStorage('user-settings', null);

To clear the entire storage with one call, consider storing all values under a single key rather than multiple keys. For example, create a key 'my-store' to store all data.

localStorage.setItem('my-store', '{"hello": "nihao"}')

const state = useStorage(
  'my-store', // key
  { hello: 'hi', greeting: 'hello' }, // default options for storage
  localStorage,
  { mergeDefaults: true } // merge behaviour
)

console.log(state.value.hello) // 'nihao', retrieved from storage
console.log(state.value.greeting) // 'hello', merged default value

This method allows you to clear the entire storage by clearing a single key.

state.value = null;

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Need help with functions in JavaScript?

I'm struggling with understanding some code related to javascript and angularjs. I came across this line - !function(a,b,c){}(x,y,z) - and I can't make sense of it. It's something new to me and I would appreciate any help in clarifying its p ...

Creating a render function that includes the img.src parameter requires careful thought and consideration

I am currently working on a dilemma where I need to dynamically adjust the height and width of an image in my render() function every time there is a state change. Here is the code snippet: render() { const imageURL = photos[this.state.currentImage]. ...

What methods can be used to control the URL and back button in a web application designed similar to an inbox in Gmail?

Similar Question: Exploring AJAX Techniques in Github's Source Browser In my application, there are essentially 2 main pages: The main page displays a list of applications (similar to an inbox) The single application page is packed with various ...

The FormData() object in Django backend is consistently found to be void of any data

I am currently experimenting with uploading an HTML form through AJAX using pure JavaScript, without jQuery. The form is put together in my template by combining three components: the CSRF token, a ModelForm, and a regular Django form (forms.Form). The vis ...

Challenges encountered while formatting Json strings for WCF service transmission

I need assistance in connecting a JavaScript application to a WCF service. The WCF Service I have includes the following method: [OperationContract] [WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.Wrapped, RequestFormat = WebMessageFor ...

Discover the nodes with the highest connections in a D3 Force Graph

As I explore the functionalities of a D3 Force Directed Graph with zoom and pan features, I encounter an issue due to my limited knowledge of d3.js. Is there a way to estimate the number of links for each node in this scenario? I am currently at a loss on ...

Having trouble with submitting the code - need help resolving the issue

I'm facing an issue with my submit cancel code. The JavaScript code I implemented for preventing the submission function on my page isn't working as expected. While it does work to a certain extent, it's not fully functional. I am seeking a ...

Efficiently transferring property values

In my current code, I have functions that retrieve specific properties from an object within an array. Since each object in the array has multiple properties, I find myself using separate functions to extract different properties. This approach is not eff ...

The error message displayed in app.js is: TypeError - it is not possible to call the 'query' method on null

Recently, I started working with node.js and encountered an issue while trying to load CSV file values into a database. The error message displayed is as follows: Error: at var stream = client.query(copyFrom('COPY menu_list FROM STDIN')); T ...

Exploring ways to display a JavaScript object on click from a .json file

As I delve into the world of javascript and json, I find myself facing a challenge. I am looking to extract information (using the Get Information function) from a json file within a javascript function triggered by an event. The catch is, I want to accom ...

Combining values and eliminating duplicates from an external API: A step-by-step guide

My API provides soccer game results in this format: results:[ { Group:"A" Home: "Fc Barcelona", Away: "Fc Porto" Score: { Home: 0, Away: 0 }, { Group:"A" Home: "AC Milan", Away: "Fc Barcelona" Score: { Home: 0, Away: 1 }, { Group:"A" Home: "FC Barcelona" ...

Is Angular Translate susceptible to race conditions when using static files for multi-language support?

Currently utilizing angular translate with the static files loader for implementing multiple languages in my project. However, I've encountered a problem where the loading of language files sometimes takes longer than loading the actual view itself, l ...

Color in the diamond shape only to a designated height

I am in search of a unique diamond shape that allows me to fill the color up to a specific height based on an attribute or variable provided. https://i.stack.imgur.com/62U6h.png. I attempted creating the diamond shape and initially considered placing it ...

When using ng-checked in Angular, the DOM may not display the element.input.checked property even when the

I am having issues with using ng-checked to automatically check a checkbox when a modal loads under certain conditions. Despite the item being checked, the condition if (item.checked) returns false. Below is the directive I am working with. app.directive ...

What is the best way to refresh my view model while using chained promises?

I've recently started learning about promises and I'm facing a challenge with updating an object in my view from two chained promises: function Test($resource, FC, UserDetailsService) { 'ngInject'; var self = this; se ...

What is the best way to implement automatic scrolling to the bottom of a materialUI drawer in React after a page refresh?

I am facing an issue with my Material UI Drawer, which contains numerous checkboxes and radio buttons for an advanced search page. Whenever a checkbox or radio button is clicked, it triggers an API request to fetch results instantly without requiring a sub ...

Troubleshooting React/Jest issues with updating values in Select elements on onChange event

I am currently testing the Select element's value after it has been changed with the following code: it("changes value after selecting another field", () => { doSetupWork(); let field = screen.getByLabelText("MySelectField") ...

Understanding how to monitor a Boolean value that fluctuates in real-time within a three.js

Currently, I am working on developing a 3D 4x4x4 tic tac toe game using three.js. In order to determine the win condition for combinations, I have created a boolean array. With a total of 64 blocks (16*4), I have initialized a boolean array of size 64 with ...

Troubleshooting issue with Django forms and JavaScript interactions

For the past day, I've been grappling with a particular issue and haven't made much progress. My setup involves using a django inline form-set, which displays all previously saved forms along with an additional empty form. To show or hide these f ...

Navigating a sortable list using jQuery

I have integrated the "sortable" script from on my web application to create a sortable list of items. While the sorting functionality works perfectly, I now need to update my server with the new order whenever changes are made. To capture the sorting ev ...