Skip to content

Commit f51f89c

Browse files
committed
fix(guess-the-word): add util to sanitize saved words item from local storage
1 parent b5d9171 commit f51f89c

File tree

2 files changed

+15
-2
lines changed

2 files changed

+15
-2
lines changed

vanilla/guess-the-word/src/services/saved-words/load.js

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import { discoveredWords } from "@/state/discovered-words";
2+
import { sanitizeStoredItem } from "./sanitize";
23
import { DIFFICULTIES_ALL } from "@/consts/difficulty";
34
import { DISCOVERED_WORDS } from "@/consts/discovered-words";
45

@@ -15,9 +16,11 @@ export const loadSavedWords = async (onLoadedWord) => {
1516
const savedItem = localStorage.getItem(DISCOVERED_WORDS.LOCAL_STORAGE_KEY);
1617

1718
if (oldSavedItem != null && savedItem == null) {
19+
const sanitized = sanitizeStoredItem(oldSavedItem);
20+
// TODO: rename to oldItemFormatAdapter()
1821
const { parseOldFormat } = await import("./parse-old");
1922

20-
await parseOldFormat(JSON.parse(oldSavedItem), async (parsedItem) => {
23+
await parseOldFormat(sanitized, async (parsedItem) => {
2124
loadWordItem(parsedItem);
2225
await onLoadedWord(parsedItem);
2326
});
@@ -30,9 +33,11 @@ export const loadSavedWords = async (onLoadedWord) => {
3033
JSON.stringify(data),
3134
);
3235
} else if (savedItem != null) {
36+
const sanitized = sanitizeStoredItem(savedItem);
3337
const { parseSavedWords } = await import("./parse");
3438

35-
await parseSavedWords(JSON.parse(savedItem), async (parsedItem) => {
39+
// TODO: rename to itemAdapter()
40+
await parseSavedWords(sanitized, async (parsedItem) => {
3641
loadWordItem(parsedItem);
3742
await onLoadedWord(parsedItem);
3843
});
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
/** @param {any} item */
2+
export function sanitizeStoredItem(item) {
3+
try {
4+
return JSON.parse(item);
5+
} catch {
6+
return [];
7+
}
8+
}

0 commit comments

Comments
 (0)