Sync
Cross-tab synchronization functionality for sharing Signify state between browser tabs.
Description
The sync feature enables real-time synchronization of Signify state across multiple browser tabs or windows. When state changes in one tab, all other tabs with the same sync key will automatically update to reflect the changes.
Configuration
Property | Type | Description |
---|---|---|
syncKey | string | Unique identifier for cross-tab synchronization |
How It Works
- Uses
BroadcastChannel
API for inter-tab communication - Automatically synchronizes state changes across tabs
- Each tab maintains its own state but receives updates from others
- Works with any data type that can be serialized
Example
typescript
import { signify } from 'react-signify';
import React from 'react';
// Shared shopping cart across tabs
const sShoppingCart = signify(
{ items: [], total: 0 },
{
syncKey: 'shopping-cart' // Same key across all tabs
}
);
// Shared user session across tabs
const sUserSession = signify(
{
isLoggedIn: false,
username: '',
lastActivity: Date.now()
},
{
syncKey: 'user-session'
}
);
function ShoppingCartComponent() {
const cart = sShoppingCart.use();
const addItem = (item: string, price: number) => {
sShoppingCart.set(({ value }) => {
value.items.push({ name: item, price });
value.total += price;
});
// This change will sync to all other open tabs
};
const clearCart = () => {
sShoppingCart.set({ items: [], total: 0 });
// Cart cleared in all tabs simultaneously
};
return (
<div>
<h2>Shopping Cart (Synced Across Tabs)</h2>
<p>Items: {cart.items.length}</p>
<p>Total: ${cart.total.toFixed(2)}</p>
<button onClick={() => addItem('Apple', 1.99)}>
Add Apple ($1.99)
</button>
<button onClick={() => addItem('Orange', 2.49)}>
Add Orange ($2.49)
</button>
<button onClick={clearCart}>
Clear Cart
</button>
<div>
<h3>Cart Items:</h3>
{cart.items.map((item, index) => (
<div key={index}>
{item.name} - ${item.price}
</div>
))}
</div>
</div>
);
}
function SessionComponent() {
const session = sUserSession.use();
const login = (username: string) => {
sUserSession.set(({ value }) => {
value.isLoggedIn = true;
value.username = username;
value.lastActivity = Date.now();
});
// Login status syncs across all tabs
};
const logout = () => {
sUserSession.set({
isLoggedIn: false,
username: '',
lastActivity: Date.now()
});
// Logout syncs across all tabs
};
return (
<div>
<h2>User Session (Synced)</h2>
{session.isLoggedIn ? (
<div>
<p>Welcome, {session.username}!</p>
<button onClick={logout}>Logout</button>
</div>
) : (
<div>
<button onClick={() => login('John Doe')}>
Login as John
</button>
</div>
)}
</div>
);
}
Use Cases:
- Shopping carts that persist across tabs
- User authentication status
- Real-time collaborative features
- Shared application state
- Multi-tab workflows
Browser Support:
- Requires
BroadcastChannel
API support - Works in all modern browsers
- Not available in some older browsers or certain environments