Skip to content

Commit

Permalink
Refactor and fix useLsState
Browse files Browse the repository at this point in the history
  • Loading branch information
jochenklar committed Jan 30, 2025
1 parent e9099ff commit 2a95493
Showing 1 changed file with 16 additions and 11 deletions.
27 changes: 16 additions & 11 deletions rdmo/core/assets/js/hooks/useLsState.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,25 +16,30 @@ const useLsState = (path, initialValue, omit = []) => {
localStorage.setItem(path, JSON.stringify(data))
}

// get the value from the local storage
const lsValue = getLs(path)
const getInitialState = () => {
// get the value from the local storage
const lsValue = getLs(path)

// return the state with the value from the local storage or the provided initialValue
if (isPlainObject(lsValue)) {
return { ...initialValue, ...lsValue }
} else if (isEmpty(lsValue)) {
return initialValue
} else {
return lsValue
}
}

// setup the state with the value from the local storage or the provided initialValue
const [value, setValue] = useState(isEmpty(lsValue) ? initialValue : lsValue)
// setup the state
const [value, setValue] = useState(getInitialState())

return [
value,
(value) => {
setLs(path, value)
setValue(value)
},
() => {
if (isPlainObject(initialValue)) {
setValue({ ...initialValue, ...getLs(path) })
} else {
setValue(initialValue)
}
}
() => setValue(getInitialState())
]
}

Expand Down

0 comments on commit 2a95493

Please sign in to comment.