docs: Missing localStorage.removeItem in persistentStorage example ("Connect to state with URL Chapter")? #3470
Answered
by
dbritto-dev
jianchoi02
asked this question in
Q&A
-
|
Hi!, I'm currently learning Zustand and going through the docs. While reading the "Connect to state with URL" guide, I noticed a potential omission in the persistentStorage custom storage example. The example uses localStorage as a fallback in both getItem and setItem. However, the removeItem method only clears the URL search parameters: import { create } from 'zustand'
import { persist, StateStorage, createJSONStorage } from 'zustand/middleware'
const getUrlSearch = () => {
return window.location.search.slice(1)
}
const persistentStorage: StateStorage = {
getItem: (key): string => {
// Check URL first
if (getUrlSearch()) {
const searchParams = new URLSearchParams(getUrlSearch())
const storedValue = searchParams.get(key)
return JSON.parse(storedValue as string)
} else {
// Otherwise, we should load from localstorage or alternative storage
return JSON.parse(localStorage.getItem(key) as string)
}
},
setItem: (key, newValue): void => {
// Check if query params exist at all, can remove check if always want to set URL
if (getUrlSearch()) {
const searchParams = new URLSearchParams(getUrlSearch())
searchParams.set(key, JSON.stringify(newValue))
window.history.replaceState(null, '', `?${searchParams.toString()}`)
}
localStorage.setItem(key, JSON.stringify(newValue))
},
// Here!!
removeItem: (key): void => {
const searchParams = new URLSearchParams(getUrlSearch())
searchParams.delete(key)
window.location.search = searchParams.toString()
},
}Should I add localStorage.removeItem(key) to this function to keep it consistent? removeItem: (key): void => {
const searchParams = new URLSearchParams(getUrlSearch())
searchParams.delete(key)
window.location.search = searchParams.toString()
// 👇 Proposed addition
localStorage.removeItem(key)
}, |
Beta Was this translation helpful? Give feedback.
Answered by
dbritto-dev
Apr 18, 2026
Replies: 1 comment 2 replies
-
|
cc @dbritto-dev |
Beta Was this translation helpful? Give feedback.
2 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@jianchoi02 yes, we need to keep consistency. btw, I'll update the docs/demos with the missing part, thanks for reporting that.