MCPcopy Create free account
hub / github.com/algolia/docsearch / createObjectStorage

Function createObjectStorage

packages/docsearch-react/src/utils/storage.ts:163–196  ·  view source on GitHub ↗
(key: string)

Source from the content-addressed store, hash-verified

161 */
162// eslint-disable-next-line @typescript-eslint/explicit-function-return-type
163export function createObjectStorage<TItem>(key: string) {
164 if (isLocalStorageSupported() === false) {
165 return {
166 setItem(_item: TItem | null): void {},
167 getItem(): TItem | null {
168 return null;
169 },
170 removeItem(): void {},
171 };
172 }
173
174 return {
175 setItem(item: TItem | null): void {
176 if (item === null) {
177 window.localStorage.removeItem(key);
178 } else {
179 safeSetLocalStorageItem(key, item);
180 }
181 },
182 getItem(): TItem | null {
183 const item = window.localStorage.getItem(key);
184 try {
185 return item ? (JSON.parse(item) as TItem) : null;
186 } catch {
187 // handle potential JSON parsing errors, e.g., corrupted data
188 window.localStorage.removeItem(key); // clear corrupted data
189 return null;
190 }
191 },
192 removeItem(): void {
193 window.localStorage.removeItem(key);
194 },
195 };
196}

Callers 1

utils.test.tsFile · 0.90

Calls 1

isLocalStorageSupportedFunction · 0.85

Tested by

no test coverage detected