Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

migrate: useSyncExternalStore instead of useState at useStore #358

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 28 additions & 19 deletions src/core/store.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useEffect, useState } from 'react';
import { useSyncExternalStore } from 'react';
import { DefaultToastOptions, Toast, ToastType } from './types';

const TOAST_LIMIT = 20;
Expand Down Expand Up @@ -157,16 +157,28 @@ export const reducer = (state: State, action: Action): State => {
}
};

const listeners: Array<(state: State) => void> = [];
const store = (() => {
let memoryState: State;
const initialState = (memoryState = { toasts: [], pausedAt: undefined });
const listeners: Set<(state: State) => void> = new Set();

let memoryState: State = { toasts: [], pausedAt: undefined };
const dispatch = (action: Action) => {
memoryState = reducer(memoryState, action);
listeners.forEach((listener) => {
listener(memoryState);
});
};

export const dispatch = (action: Action) => {
memoryState = reducer(memoryState, action);
listeners.forEach((listener) => {
listener(memoryState);
});
};
const getState = () => memoryState;

const subscribe = (listener: () => void) => {
listeners.add(listener);
return () => listeners.delete(listener);
};
const getInitialState = () => initialState;

return { dispatch, getState, subscribe, getInitialState };
})();

export const defaultTimeouts: {
[key in ToastType]: number;
Expand All @@ -178,17 +190,14 @@ export const defaultTimeouts: {
custom: 4000,
};

export const dispatch = store.dispatch;

export const useStore = (toastOptions: DefaultToastOptions = {}): State => {
const [state, setState] = useState<State>(memoryState);
useEffect(() => {
listeners.push(setState);
return () => {
const index = listeners.indexOf(setState);
if (index > -1) {
listeners.splice(index, 1);
}
};
}, [state]);
const state = useSyncExternalStore(
store.subscribe,
store.getState,
store.getInitialState
);

const mergedToasts = state.toasts.map((t) => ({
...toastOptions,
Expand Down