'Failed to execute 'setItem' on 'Storage': Setting the value of 'state' exceeded the quota (localStorage.clear() won't work)

In my React project I use Redux where I save the serialized state:

const saveState = (state: any) => {
    try {
        const serializedState = JSON.stringify(state);

        localStorage.removeItem('state');
        localStorage.clear();
        localStorage.setItem('state', serializedState);

    } catch (e) {
        console.log(e);
        let _lsTotal = 0, _xLen, _x; for (_x in localStorage) { if (!localStorage.hasOwnProperty(_x)) { continue; } _xLen = ((localStorage[_x].length + _x.length) * 2); _lsTotal += _xLen; console.log(_x.substr(0, 50) + " = " + (_xLen / 1024).toFixed(2) + " KB") }; console.log("Total = " + (_lsTotal / 1024).toFixed(2) + " KB");
    }};

Since I came upon the 'Setting the value of 'state' exceeded the quota' error I tried to clear the local storage (see above). Yet I still get this error, and the code in the catch part shows 0.00KB of the storage:

DOMException: Failed to execute 'setItem' on 'Storage': Setting the value of 'state' exceeded the quota.
at saveState (http://localhost:xxxx/static/js/main.chunk.js:16322:18)
at http://localhost:xxxx/static/js/main.chunk.js:16350:5
at invokeFunc (http://localhost:xxxx/static/js/1.chunk.js:276358:19)
at trailingEdge (http://localhost:xxxx/static/js/1.chunk.js:276403:14)
at timerExpired (http://localhost:xxxx/static/js/1.chunk.js:276391:14)
Store.ts:1967 Total = 0.00 KB

How to avoid this error?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source