-
Notifications
You must be signed in to change notification settings - Fork 2
/
answers.js
89 lines (69 loc) · 1.96 KB
/
answers.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
import { v4 as uuid } from 'uuid'
import create from 'zustand'
import t from '../i18n'
const LOCAL_KEY = 'answers'
const getInitialAnswer = () => ({
id: uuid(),
title: t('NEW_ANSWER'),
date: Date.now(),
})
const getFromLocalStorage = (key, initialValue) => {
try {
const item = window.localStorage.getItem(key)
return item ? JSON.parse(item) : initialValue
} catch (error) {
return initialValue
}
}
const setLocalStorage = (answers) => {
try {
localStorage.setItem(LOCAL_KEY, JSON.stringify(answers))
} catch (error) {
console.warn('Failed to store items in local storage', error)
}
}
const persistedAnswers = getFromLocalStorage(LOCAL_KEY, [getInitialAnswer()])
const useAnswersStore = create((set, get) => ({
answers: persistedAnswers,
selectedAnswerId: persistedAnswers[0]?.id ?? null,
selectAnswer: (selectedAnswerId) => set({ selectedAnswerId }),
addAnswer: (file = {}) => {
const id = uuid()
const answers = [
{
...file,
id,
date: file.date || Date.now(),
title: file.title || t('NEW_ANSWER'),
},
...get().answers,
]
set({ answers, selectedAnswerId: id })
setLocalStorage(answers)
return id
},
updateAnswer: (id, answer) => {
const prevAnswers = get().answers
const answerIndex = prevAnswers.findIndex((answer) => answer.id === id)
if (answerIndex > -1) {
const updatedAnswer = {
...prevAnswers[answerIndex],
...answer,
}
const answers = prevAnswers.map((originalAnswer, i) =>
i === answerIndex ? updatedAnswer : originalAnswer
)
set({ answers })
setLocalStorage(answers)
}
},
deleteAnswer: (id) => {
const answers = get().answers.filter((answer) => answer.id !== id)
if (answers.length === 0) {
answers.push(getInitialAnswer())
}
set({ answers, selectedAnswerId: answers[0]?.id })
setLocalStorage(answers)
},
}))
export default useAnswersStore