Skip to content

Instantly share code, notes, and snippets.

@ajnart
Last active July 11, 2023 12:36
Show Gist options
  • Save ajnart/dce0902a18c6f274b840c94c549f446e to your computer and use it in GitHub Desktop.
Save ajnart/dce0902a18c6f274b840c94c549f446e to your computer and use it in GitHub Desktop.
Small zustand + immer POC
import { Button, Center, Stack } from '@mantine/core';
import { Dashboard, Widgets, useDashboardStore } from '~/tools/useDashboard';
export default function HomePage() {
const { setCurrentDashboard, currentDashboard, addDashboard } = useDashboardStore(
(state) => state
);
return (
<>
<Center>
<Stack p={200}>
Current dashboard : {currentDashboard?.name || 'none'}
<Button
onClick={() => {
const newDashboard: Dashboard = {
id: 1,
name: 'Dashboard 1',
widgets: new Widgets([]),
};
addDashboard(newDashboard);
setCurrentDashboard(newDashboard);
console.log('Widget with the longest name', currentDashboard?.widgets.getLongestName);
}}
>
Set dashboard
</Button>
Widget with the longest name : {currentDashboard?.widgets.getLongestName().name || 'none'}
</Stack>
</Center>
</>
);
}
import { create } from 'zustand';
import { immer } from 'zustand/middleware/immer';
type Widget = {
id: number;
name: string;
};
export class Widgets {
widgets: Widget[];
constructor(widgets: Widget[]) {
this.widgets = widgets;
}
// Function to get the widget with the longest name
getLongestName() {
return this.widgets.reduce((acc, widget) => {
if (widget.name.length > acc.name.length) {
return widget;
}
return acc;
});
}
}
export type Dashboard = {
id: number;
name: string;
widgets: Widgets;
};
type DashboardManager = {
dashboards: Dashboard[];
currentDashboard: Dashboard | undefined;
addDashboard(dashboard: Dashboard): void;
removeDashboard(id: number): void;
setCurrentDashboard(dashboard: Dashboard): void;
};
export const useDashboardStore = create(
immer<DashboardManager>((set) => ({
currentDashboard: undefined,
dashboards: [],
setCurrentDashboard(dashboard: Dashboard) {
set((state) => {
state.currentDashboard = dashboard;
});
},
addDashboard(dashboard: Dashboard) {
set((state) => {
state.dashboards.push(dashboard);
});
},
removeDashboard(id: number) {
set((state) => {
state.dashboards = state.dashboards.filter((dashboard) => dashboard.id !== id);
});
},
}))
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment