A comprehensive React state management library for Buzzebees applications, providing both traditional React Context and modern Zustand implementations.
This library centralizes business logic and state management for Buzzebees applications. It provides a collection of providers for authentication, user management, shopping cart, notifications, and more.
This library supports two different state management approaches, allowing you to choose the one that best fits your application:
Uses React Context API with hooks for state management. Requires provider components to be wrapped around your application.
Uses Zustand for lightweight, fast state management without provider wrappers. Stores can be used directly in components.
npm install @bzbs/react-providers
This library requires React 18 or 19:
npm install react@^18.0.0 react-dom@^18.0.0
# or
npm install react@^19.0.0 react-dom@^19.0.0
When using Context providers, you need to wrap your application with the necessary providers:
// App.tsx
import React from 'react';
import {
AuthProvider,
UserProvider,
CartProvider,
AlertProvider,
AppLocaleProvider,
BuzzebeesServiceProvider,
EN,
} from '@bzbs/react-providers/context';
import { BzbsService } from '@bzbs/react-api-client';
// Your service instance
const bzbsService = new BzbsService(/* your config */);
// Your token management functions
const tokenFunctions = {
getToken: async () => localStorage.getItem('token'),
setToken: (token: string) => localStorage.setItem('token', token),
removeToken: () => localStorage.removeItem('token'),
};
function App() {
return (
<BuzzebeesServiceProvider bzbsService={bzbsService}>
<AppLocaleProvider initLocale={EN}>
<AuthProvider tokenFunctions={tokenFunctions}>
<UserProvider>
<CartProvider>
<AlertProvider>
<YourAppComponents />
</AlertProvider>
</CartProvider>
</UserProvider>
</AuthProvider>
</AppLocaleProvider>
</BuzzebeesServiceProvider>
);
}
// components/LoginForm.tsx
import React from 'react';
import { useAuthContext, useAlertContext } from '@bzbs/react-providers/context';
function LoginForm() {
const { actions: authActions, isLoading, isLoggedIn } = useAuthContext();
const { openAlert } = useAlertContext();
const handleLogin = async (username: string, password: string) => {
try {
const result = await authActions.loginWithUsernamePassword(username, password);
if (result.type === 'success') {
openAlert({
title: 'Success',
content: 'Login successful!',
onClose: () => console.log('Alert closed'),
});
}
} catch (error) {
console.error('Login failed:', error);
}
};
if (isLoggedIn) {
return <div>Welcome! You are logged in.</div>;
}
return (
<div>
<button onClick={() => handleLogin('user', 'pass')} disabled={isLoading}>
{isLoading ? 'Logging in...' : 'Login'}
</button>
</div>
);
}
With Zustand, you don't need provider wrappers. Just configure the stores and use them directly:
// App.tsx (setup)
import React, { useEffect } from 'react';
import { useBuzzebeesAppStore, useLocaleStore, EN } from '@bzbs/react-providers/zustand';
import { BzbsService } from '@bzbs/react-api-client';
function App() {
const configure = useBuzzebeesAppStore((state) => state.configure);
const setAppLocale = useLocaleStore((state) => state.setAppLocale);
// Configure stores on app initialization
useEffect(() => {
// Configure main app store with all dependencies
configure({
appId: 'your-app-id',
appName: 'Your App Name',
bzbsService: new BzbsService(/* your config */),
uuid: 'device-uuid',
clientVersion: '1.0.0',
os: 'web',
platform: 'web',
fcmToken: '',
deviceNotificationEnabled: true,
urls: {
webCallback: 'https://your-app.com/callback',
cart: 'https://your-app.com/cart',
},
tokenFunctions: {
getToken: async () => localStorage.getItem('token'),
setToken: (token: string) => localStorage.setItem('token', token),
removeToken: () => localStorage.removeItem('token'),
},
tokenType: 'auth_token', // or 'jwt'
defaultDashboardConfig: '',
defaultDashboardMode: 'main',
defaultMenuConfig: '',
defaultCampaignConfig: '',
});
// Set initial locale
setAppLocale(EN);
}, [configure, setAppLocale]);
return <YourAppComponents />;
}
If you prefer to configure stores individually:
// App.tsx (alternative setup)
import React, { useEffect } from 'react';
import { useBuzzebeesAppStore, useAuthStore, useLocaleStore, EN } from '@bzbs/react-providers/zustand';
function App() {
const setBzbsService = useBuzzebeesAppStore((state) => state.setBzbsService);
const setTokenFunctions = useBuzzebeesAppStore((state) => state.setTokenFunctions);
const setAppLocale = useLocaleStore((state) => state.setAppLocale);
useEffect(() => {
// Configure individual stores
setBzbsService(yourBzbsServiceInstance);
setTokenFunctions({
getToken: async () => localStorage.getItem('token'),
setToken: (token: string) => localStorage.setItem('token', token),
removeToken: () => localStorage.removeItem('token'),
});
setAppLocale(EN);
}, [setBzbsService, setTokenFunctions, setAppLocale]);
return <YourAppComponents />;
}
// components/LoginForm.tsx
import React from 'react';
import { useAuthStore, useAlertStore } from '@bzbs/react-providers/zustand';
function LoginForm() {
const { loginWithUsernamePassword, isLoading, isLoggedIn } = useAuthStore();
const openAlert = useAlertStore((state) => state.openAlert);
const handleLogin = async (username: string, password: string) => {
try {
const result = await loginWithUsernamePassword(username, password);
if (result.type === 'success') {
openAlert({
title: 'Success',
content: 'Login successful!',
onClose: () => console.log('Alert closed'),
});
}
} catch (error) {
console.error('Login failed:', error);
}
};
if (isLoggedIn) {
return <div>Welcome! You are logged in.</div>;
}
return (
<div>
<button onClick={() => handleLogin('user', 'pass')} disabled={isLoading}>
{isLoading ? 'Logging in...' : 'Login'}
</button>
</div>
);
}
- Auth - Authentication, login, logout, token management, OTP, password reset
- User - User profile, points, badges, user management, event listeners
- Cart - Shopping cart operations and URL generation
- Locale - Internationalization and localization (EN/TH support)
- Buzzebees Service - Service configuration and dependency injection
- Alert - Alert dialogs and notifications
- Confirm - Confirmation dialogs
- Popup - Popup modals
- Loading Indicator - Loading states and indicators
- Address - Shipping and tax address management with CRUD operations
- Campaign Detail - Individual campaign management, redemption, favorites
- Campaigns - Campaign listings with pagination and filtering
- Categories - Category management with locale support
- Consent - Privacy consent and cookie management
- Coupon - Coupon code processing and validation
- Dashboard - Main and sub-dashboard content management
- Maintenance - Maintenance mode detection and handling
- Notification - Push notification management and read status
- Point Log - Point transaction history with pagination
- Purchase - Purchase history and redemption tracking
- Registration - User registration flow with OTP and consent
- Zipcode - Address lookup and province/district selection
- Buzzebees App - Main configuration store that manages app settings and dependencies
All providers have corresponding Zustand stores that maintain the same functionality while providing the benefits of Zustand's lightweight and flexible state management.
- Remove Provider Wrappers: Remove Context providers from your App component
-
Configure Stores: Set up store configuration in your App component using
configure
method or individual setters -
Update Imports: Change import paths from
/context
to/zustand
- Update Usage: Replace Context hooks with Zustand store hooks
- Add Provider Wrappers: Wrap your App with necessary providers
- Remove Store Configuration: Remove store setup code
-
Update Imports: Change import paths from
/zustand
to/context
- Update Usage: Replace Zustand hooks with Context hooks
This library uses tsup for building, which provides:
- TypeScript compilation
- CommonJS and ESM output formats
- Declaration file generation
- Source maps
npm run build # Build the library
npm run test # Run tests with coverage
npm run format # Format code with Prettier
npm run patch # Build, patch version, and publish
npm run minor # Build, minor version, and publish
npm run major # Build, major version, and publish
When adding new providers/stores:
- Create the Context Provider in
src/providers/
- Create the corresponding Zustand store in
src/stores/
- Export both in their respective entry points (
context.ts
andzustand.ts
) - Add exports to
src/providers/index.ts
andsrc/stores/index.ts
- Update this README with usage examples and add to the Available Providers/Stores list
ISC