Skip to content

Commit

Permalink
✨ return Promise when setting or removing state
Browse files Browse the repository at this point in the history
  • Loading branch information
astoilkov committed Oct 31, 2024
1 parent 448deab commit 3f953ae
Showing 1 changed file with 9 additions and 9 deletions.
18 changes: 9 additions & 9 deletions index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { Dispatch, SetStateAction } from "react";
import type { SetStateAction } from "react";
import { useCallback, useMemo, useState, useSyncExternalStore } from "react";
import { DbStorage } from "local-db-storage";

Expand All @@ -16,8 +16,8 @@ export type StorageStateOptions<T> = {
// - first two values are the same as `useState`
export type DbState<T> = [
state: T,
setState: Dispatch<SetStateAction<T>>,
removeItem: () => void,
setState: (value: SetStateAction<T>) => Promise<void>,
removeItem: () => Promise<void>,
];

export default function useDb(
Expand Down Expand Up @@ -74,17 +74,17 @@ function useStorage<T>(
);

const setState = useCallback(
(newValue: SetStateAction<T | undefined>): void => {
(newValue: SetStateAction<T | undefined>): Promise<void> => {
const hasPrev = syncData.has(key);
const prev = hasPrev
const prev = syncData.has(key)
? (syncData.get(key) as T | undefined)
: defaultValue;
const next =
newValue instanceof Function ? newValue(prev) : newValue;
if (optimistic) {
syncData.set(key, next);
triggerCallbacks(key);
dbStorage.setItem(key, next).catch(() => {
return dbStorage.setItem(key, next).catch(() => {
if (hasPrev) {
syncData.set(key, prev);
} else {
Expand All @@ -93,7 +93,7 @@ function useStorage<T>(
triggerCallbacks(key);
});
} else {
dbStorage.setItem(key, next).then(() => {
return dbStorage.setItem(key, next).then(() => {
syncData.set(key, next);
triggerCallbacks(key);
});
Expand All @@ -108,14 +108,14 @@ function useStorage<T>(
if (optimistic) {
syncData.delete(key);
triggerCallbacks(key);
dbStorage.removeItem(key).catch(() => {
return dbStorage.removeItem(key).catch(() => {
if (hasPrev) {
syncData.set(key, prev);
triggerCallbacks(key);
}
});
} else {
dbStorage.removeItem(key).then(() => {
return dbStorage.removeItem(key).then(() => {
syncData.delete(key);
triggerCallbacks(key);
});
Expand Down

0 comments on commit 3f953ae

Please sign in to comment.