GitHub Homepage React Spectrum Libraries Legal Notice

@wuespace/telestion-client-core

Install using

npm install @wuespace/telestion-client-core

Exported Members

You can access these members by importing the module:

import { member } from '@wuespace/telestion-client-core';

TelestionClient (...)

function TelestionClient (
   { title = 'Telestion Client', wrapper, children } : TelestionClientProps
) : any

The "root" component of a Telestion Client.

Every part of a Telestion Client application should be a child of this component.

@see:

@example:

A very simple Telestion Client

import ReactDOM from 'react-dom';

ReactDOM.render(
	<TelestionClient />,
	document.getElementById('root')
);

TelestionClient

TelestionClientProps

interface TelestionClientProps

React Props of TelestionClient

For more information about React Props, please look here: https://reactjs.org/docs/components-and-props.html

Properties

title ?

Type: string

The title of the application.

The title can be used with the useTitle hook to get a consistent title of the application.

wrapper ?

Type: (children: ReactNode) => ReactElement

A function that will "wrap" the children into additional contexts, setups, HOCs, ...

@param:

children - the children components of the TelestionClient component

@returns:

a valid react element

children ?

Type: ReactNode

Additional children given to the Telestion Client. It renders them in his context.

Pages (...)

function Pages (
   { preNodes, postNodes, children } : PagesProps
) : any

The router of the application. Here are all pages managed.

Every page defines a routing object that is attached to the actual component.

If you want to write some pages, please take a look at @wuespace/telestion-client-types#Routing for more information.

@see:

@example:

function MyPages() {
	return (
		<Pages>
			<LoginPage />
			<DashboardPage />
			<NotFoundPage />
		</Pages>
	);
}

Pages

PagesProps

interface PagesProps

React Props of Pages

For more information about React Props, please look here: https://reactjs.org/docs/components-and-props.html

Properties

preNodes ?

Type: ReactNode

React nodes that are always rendered above the active page. E.g. useful for an application header.

postNodes ?

Type: ReactNode

React nodes that are always rendered below the active page. E.g. useful for an application footer.

children

Type: ReactNode

Pages that the application can have. The Pages component renders them based on the application state.

Preferences (...)

function Preferences (
   { children } : PreferencesProps
) : any

Wrapper component for Group and Variable which defining application preferences and their renderers.

@see:

@see:

@see:

@see:

@example:

function MyPreferences() {
	return (
		<Preferences>
			<Variable name="myPref">
				{(value, setValue) => (
					<input value={value} onChange={event => setValue(event.target.value)} />
				)}
			</Variable>
			<Group name="SomeGroup">
				<Variable name="groupedPref">
					{(value, setValue) => (
						<input value={value} onChange={event => setValue(event.target.value)} />
					)}
				</Variable>
			</Group>
		</Preferences>
	);
}

Preferences

PreferencesProps

interface PreferencesProps

React Props of Preferences

For more information about React Props, please look here: https://reactjs.org/docs/components-and-props.html

Properties

children

Type: ReactNode

Usually components of the type Group and Variable to build an application preferences structure.

Group (...)

function Group (
   { name, children } : GroupProps
) : any

Defines a group of variables which are typically Variable components. It gives Variable a group context.

@see:

@see:

@see:

@see:

@example:

function MyPreferences() {
	return (
		<Preferences>
			<Variable name="myPref">
				{(value, setValue) => (
					<input value={value} onChange={event => setValue(event.target.value)} />
				)}
			</Variable>
			<Group name="SomeGroup">
				<Variable name="groupedPref">
					{(value, setValue) => (
						<input value={value} onChange={event => setValue(event.target.value)} />
					)}
				</Variable>
			</Group>
		</Preferences>
	);
}

Group

GroupProps

interface GroupProps

React Props of Group

For more information about React Props, please look here: https://reactjs.org/docs/components-and-props.html

Properties

name

Type: GroupSelector

The name of the group of variables.

children

Type: ReactNode

Usually components of the type Variable to build an application preferences structure.

Variable (...)

function Variable (
   { name, initialValue, children } : VariableProps
) : any

Component to define a preference for the application and a renderer for this preference.

If it is wrapped in the Group component, the renderer will be registered for the preference in that group otherwise for the preference in the global scope.

@see:

@see:

@see:

@see:

@example:

function MyPreferences() {
	return (
		<Preferences>
			<Variable name="myPref">
				{(value, setValue) => (
					<input value={value} onChange={event => setValue(event.target.value)} />
				)}
			</Variable>
			<Group name="SomeGroup">
				<Variable name="groupedPref">
					{(value, setValue) => (
						<input value={value} onChange={event => setValue(event.target.value)} />
					)}
				</Variable>
			</Group>
		</Preferences>
	);
}

Variable

VariableProps

interface VariableProps

React Props of Variable

For more information about React Props, please look here: https://reactjs.org/docs/components-and-props.html

Properties

name

Type: PrefSelector

The name of the preference.

initialValue ?

Type: PrefValue

The initial value of the preference.

children

Type: PrefRenderer

The renderer function for the preference.

useBroadcast (...)

function useBroadcast (
   address : ChannelAddress
) : BroadcastFunction

Sends a broadcast on the specified address with the returned function.

@param:

address - the channel with the address to broadcast to

@returns:

a function that broadcasts a message

@throws:

TypeError - if there is no eventbus instance

@see:

@see:

@example:

const broadcast = useBroadcast('address:hello-world');

const handleClick = () => {
  broadcast('Hello World');
};

return <button onClick={handleClick}>Broadcast a hello world</button>;

useChannel (...)

function useChannel < T : JsonSerializable = JsonSerializable > (
   address : ChannelAddress ,
   onUpdate : (data: T) => void
) : void

Subscribes to an event bus channel specified by an address.

Important note:

Please preserve the identity of the onUpdate function to minimize registers and unregisters on the eventbus.

For example use useCallback from React, or if you only interested on the most recent data use useChannelLatest instead. It handles the caveats for you.

@param:

address - the channel with the address to receive data from

@param:

onUpdate - callback that gets called on new received data

@typeParam:

T - the type of the received data (defaults to JSON serializable data)

@throws:

TypeError - if there is no eventbus instance

@see:

@see:

@see:

@example:

const [state, setState] = useState<JSONSerializable>();

const cb = useCallback((data) => {
  setState(data);
}, []);

useChannel('channel:test-data', cb);

return <p>Content: {state}</p>;

useChannelLatest (...)

function useChannelLatest < T : JsonSerializable = JsonSerializable > (
   address : ChannelAddress
) : T | undefined

Gets the latest information broadcast from a channel specified by an address.

@param:

address - the channel with the address to receive data from

@returns:

the last received message or undefined if no message was received yet

@typeParam:

T - the type of the received data (defaults to JSON serializable data)

@throws:

if there is no eventbus instance

@see:

@see:

@example:

const latestPos = useChannelLatest('address:position');
return <p>Latest position: {latestPos}</p>;

useRequest (...)

function useRequest < T : JsonSerializable = JsonSerializable > (
   address : ChannelAddress
) : SendFunction<T>

Sends a message on the specified address and get the first reply via a callback.

@param:

address - the channel with the address to send the message to

@returns:

a function that sends a message and registers a one-time callback

@typeParam:

T - the type of the received data in the callback (defaults to JSON serializable data)

@throws:

TypeError - if there is no eventbus instance

@see:

@see:

@example:

const [answer, setAnswer] = useState<JSONSerializable>();
const send = useRequest('address:send-my-anything');

const handleClick = () => {
  send('Ping', message => {
    setAnswer(message);
  });
};

return (
  <>
    <button onClick={handleClick}>Send message</button>
    <p>{answer}</p>
  </>
);

SendFunction

type SendFunction < T : JsonSerializable >

Alias for: (message: JsonSerializable, callback: (message: T) => void) => void

Sends a message to the event bus and get the first reply via a callback.

@typeParam:

T - the type of the received data in the callback (defaults to JSON serializable data)

usePrefValue (...)

function usePrefValue (
   group : GroupSelector ,
   preference : PrefSelector
) : PrefValue | undefined

Returns the current value of a preference in a group.

If the group selector is null the preference in the global scope will be used.

@param:

group - the group of the preference

@param:

preference - the name of the preference

@returns:

the current value of the preference

@see:

@example:

const myPref = usePrefValue('myGroup', 'myPref');

return <div>{myPref}</div>;

useTitle (...)

function useTitle ( ) : PrefValue | undefined

Returns the title of the application.

@see:

@see:

@example:

Displays the title of the application

const title = useTitle();
return <p>Application title: {title}</p>;

useEventBusManager (...)

function useEventBusManager (
   options : EventBusManagerOptions = {}
) : void

Handles the event bus creation automatically.

It opens and closes the event bus based on the application authentication state.

If a user is logged in, the event bus will automatically be opened, and if the user logs out again or nobody is logged in the event bus will be closed.

@param:

options - optional parameters to configure the event bus manager

@example:

Commonly used as:

import { TelestionClient, useEventBusManager } from '@wuespace/telestion-client-core';

export function App() {
	useEventBusManager({
		options: { pingInterval: 2000 },
		onOpen: () => console.log('Open...'),
		onClose: () => console.log('Close...')
	});

	return (
		<TelestionClient title="My Application">
			...
		</TelestionClient>
	);
}

EventBusManagerOptions

interface EventBusManagerOptions

Optional parameters to configure the event bus manager.

Properties

options ?

Type: Options

Optional parameters for the event bus instance.

onOpen ?

Type: () => void

Gets called, when the event bus manager detects a valid authentication and opens an event bus connection.

onClose ?

Type: () => void

Gets called, when the event bus manager detects a change in authentication and closes the event bus connection.

useAuth

const : UseBoundStore<StoreApi<AuthState>>

Returns the authentication state and actions to interact with. A selector can be defined to pick out parts of the store. If correctly set up, the function only triggers a rerender if the selected values have changed.

For more information about state management in Zustand, take a look at their [https://github.com/pmndrs/zustand | GitHub page](#https://github.com/pmndrs/zustand | GitHub page).

@param:

selector - optional selector function which picks the specified elements out of the store

@param:

equalityFn - optional equality function to check for state updates on the picked elements

@returns:

the picked elements in the selector function

@see:

@see:

@see:

@see:

@example:

Fetch current authentication state from the store:

// React component or hook context
const auth = useAuth(state => state.auth);

if (auth) {
	console.log(`User ${auth.username} is logged in`);
} else {
	console.log('Nobody is logged in');
}

Performance optimized and type-safe fetching from the store:

import { useCallback, ReactNode } from 'react';
import { StateSelector } from 'zustand';
import shallow from 'zustand/shallow';
import { useAuth, AuthState } from '@wuespace/telestion-client-core';

// selector does not depend on scope, so it's better to define it outside
// to not re-declare it on every render
const selector: StateSelector<
	AuthState,
	{
		signIn: AuthState['signIn'],
		signOut: AuthState['signOut']
	}
> = state => ({
	signIn: state.signIn,
	signOut: state.signOut
});

export function MyComponent(): ReactNode {
	const { signIn, signOut } = useAuth(selector, shallow);

	const logIn = useCallback(
		() => signIn('http://localhost:9870/bridge/', 'alice', '12345'),
		[]
	);

	const logOut = useCallback(() => signOut(), []);

	return (
		<div>
			<button onClick={logIn}>Login</button>
			<button onClick={logOut}>Logout</button>
		</div>
	);
}

useEventBus

const : UseBoundStore<StoreApi<EventBusState>>

Returns the event bus state and actions to interact with. A selector can be defined to pick out parts of the store. If correctly set up, the function only triggers a rerender if the selected values have changed.

For more information about state management in Zustand, take a look at their [https://github.com/pmndrs/zustand | GitHub page](#https://github.com/pmndrs/zustand | GitHub page).

@param:

selector - optional selector function which picks the specified elements out of the store

@param:

equalityFn - optional equality function to check for state updates on the picked elements

@returns:

the picked elements in the selector function

@see:

@see:

@see:

@see:

@example:

Fetch current connection state from the store:

// React component or hook context
const connectionState = usePreferences(state => state.connectionState);
return <p>Connection State: {connectionState}</p>;

Performance optimized and type-safe fetching from the store:

import { useCallback, ReactNode } from 'react';
import { StateSelector } from 'zustand';
import shallow from 'zustand/shallow';
import {
	useEventBus,
	EventBusState
} from '@wuespace/telestion-client-core';
import { someRenderer } from './some-renderer';

// selector does not depend on scope, so it's better to define it outside
// to not re-declare it on every render
const selector: StateSelector<
	EventBusState,
	{
		open: EventBusState['openEventBus'],
		close: PreferencesState['closeEventBus']
	}
> = state => ({
	open: state.openEventBus,
	close: state.closeEventBus
});

export function MyComponent(): ReactNode {
	const { open, close } = useEventBus(selector, shallow);

	const openEB = useCallback(
		() => open('http://localhost:9870/bridge/'),
		[]
	);

	const closeEB = useCallback(
		() => close(),
		[]
	);

	return (
		<div>
			<button onClick={openEB}>Open event bus</button>
			<button onClick={closeEB}>Close event bus</button>
		</div>
	);
}

useNotifications

const : UseBoundStore<StoreApi<NotificationState>>

Returns the notification state and actions to interact with. A selector can be defined to pick out parts of the store. If correctly set up, the function only triggers a rerender if the selected values have changed.

For more information about state management in Zustand, take a look at their [https://github.com/pmndrs/zustand | GitHub page](#https://github.com/pmndrs/zustand | GitHub page).

@param:

selector - optional selector function which picks the specified elements out of the store

@param:

equalityFn - optional equality function to check for state updates on the picked elements

@returns:

the picked elements in the selector function

@see:

@see:

@see:

@see:

@example:

Fetch stored notifications from the store:

function Notifications() {
	const notifications = useNotifications(state => state.notifications);

	return (
		<ul>
			{notifications.map(notification => (
				<li>{`${notification.message}: ${notification.description}`}</li>
			)}
		</ul>
	);
}

Performance optimized and type-safe fetching from the store:

import { useCallback, ReactNode } from 'react';
import { StateSelector } from 'zustand';
import shallow from 'zustand/shallow';
import {
	useNotifications,
	NotificationState
} from '@wuespace/telestion-client-core';

// selector does not depend on scope, so it's better to define it outside
// to not re-declare it on every render
const selector: StateSelector<
	NotificationState,
	{
		showAll: NotificationState['showAll'],
		mute: NotificationState['mute'],
		unmute: NotificationState['unmute']
	}
> = state => ({
	showAll: state.showAll,
	mute: state.mute,
	unmute: state.unmute
});

function MyComponent() {
	const { showAll, mute, unmute } = useAuth(selector, shallow);

	return (
		<div>
			<button onClick={showAll}>Show all notifications</button>
			<button onClick={mute}>Mute all new notifications</button>
			<button onClick={unmute}>Unmute all new notifications</button>
		</div>
	);
}

usePreferences

const : UseBoundStore<StoreApi<PreferencesState>>

Returns the preferences application state and actions to interact with. A selector can be defined to pick out parts of the store. If correctly set up, the function only triggers a rerender if the selected values have changed.

For more information about state management in Zustand, take a look at their [https://github.com/pmndrs/zustand | GitHub page](#https://github.com/pmndrs/zustand | GitHub page).

@param:

selector - optional selector function which picks the specified elements out of the store

@param:

equalityFn - optional equality function to check for state updates on the picked elements

@returns:

the picked elements in the selector function

@see:

@see:

@see:

@see:

@example:

Fetch current preference from the store:

// React component or hook context
const myGroupSelector = 'my-group';
const myVarSelector = 'my-var';
const myPreference = usePreferences(
	state => state.preferences[myGroupSelector][myVarSelector]
);

Performance optimized and type-safe fetching from the store:

import { useCallback, ReactNode } from 'react';
import { StateSelector } from 'zustand';
import shallow from 'zustand/shallow';
import {
	usePreferences,
	PreferencesState
} from '@wuespace/telestion-client-core';
import { someRenderer } from './some-renderer';

// selector does not depend on scope, so it's better to define it outside
// to not re-declare it on every render
const selector: StateSelector<
	PreferencesState,
	{
		setValue: PreferencesState['setValue'],
		setRenderer: PreferencesState['setRenderer']
	}
> = state => ({
	setValue: state.setValue,
	setRenderer: state.setRenderer
});

export function MyComponent(): ReactNode {
	const { setValue, setRenderer } = usePreferences(selector, shallow);

	const updateValue = useCallback(
		() => setValue('null', 'title', 'New Application Title!'),
		[]
	);

	const updateRenderer = useCallback(
		() => setRenderer('null', 'title', someRenderer),
		[]
	);

	return (
		<div>
			<button onClick={updateValue}>Update Value</button>
			<button onClick={updateRenderer}>Update Renderer</button>
		</div>
	);
}

PreferencesState

interface PreferencesState

The preference state and actions of the Telestion Client Core.

Defines the preferences store and functions to change the store.

Properties

preferences

Type: PreferencesStore

Stores the registered preferences as groups of selector-value pair.

To add, update and remove the preference value use setValue.

To add, update and remove the preference renderer use setRenderer instead.

@see:

@see:

@example:

const preference = usePreferences(
   state => state.preferences['group']['preference'].value
);

return <div>{preferences}</div>;
setValue

Type: ( group: GroupSelector, preference: PrefSelector, newValue: PrefValue ) => void

Adds, updates or removes a preference value from the preference store.

To access the preference a group and a preference selector is needed.

If the group selector is null the preference in the global scope will be used.

@param:

group - the group of the preference

@param:

preference - the preference name

@param:

newValue - the new value of the preference

@see:

@see:

@see:

@see:

@example:

const update = usePreferences(state => state.updateValue);
const handleClick = () => update('group', 'preference', 'My new value!');

return <button onClick={handleClick}>Set Preference</button>;
setRenderer

Type: ( group: GroupSelector, preference: PrefSelector, newRenderer: PrefRenderer ) => void

Adds, updates or removes a preference renderer from the preference store.

To access the preference a group and a preference selector is needed.

If the group selector is null the preference in the global scope will be used.

@param:

group - the group of the preference

@param:

preference - the preference name

@param:

newRenderer - the new renderer for the preference

@see:

@see:

@see:

@example:

const update = usePreferences(state => state.updateValue);
const renderer = (value, setValue) => (
   <TextInput initialValue={value} onSubmit={setValue} />
);

const handleClick = () => update('group', 'preference', renderer);

return <button onClick={handleClick}>Set Renderer</button>;
removePreference

Type: (group: GroupSelector, preference: PrefSelector) => void

Removes a preference from the store.

To access the preference a group and a preference selector is needed.

If the group selector is null the preference in the global scope will be used.

@param:

group - the group of the preference

@param:

preference - the name of the preference that will be removed

@see:

@see:

removeGroup

Type: (group: GroupSelector) => void

Removes an entire group of preferences from the store.

To access the group and a selector is needed.

If the group selector is null the preference in the global scope will be used.

@param:

group - the name of the group that will be removed

@see:

@see:

setStore

Type: (newStore: PreferencesStore) => void

Overwrites the current preferences store with the specified store.

@param:

newStore - the new preferences store to use

@see:

@see:

NotificationState

interface NotificationState

The notification state and actions of the Telestion Client Core.

Stores and handles the notifications of the application.

Properties

notifications

Type: Array<Notification>

Stores all notifications. Every notification has a isDismissed flag which indicates that the notification was shown in the current environment.

To add notifications, call NotificationState.add. To mute all further notifications, call NotificationState.mute.

@see:

@see:

@example:

Log all new notifications

function useNotificationLogger() {
	const { notifications, dismiss } = useNotifications(state => ({
	  notifications: state.notifications,
		dismiss: state.dismiss
	}));

	useEffect(() => {
		// filter out all new notifications
		const new = notifications.filter(notification => !notification.isDismissed);
		// log them
		new.forEach(notification => {
			console.log(`${notification.message}: ${notification.description}`);
		});
		// and dismiss them to not log them again
		dismiss(new);
	}, [notification, dismiss]);
}
isMuted

Type: boolean

If true all notifications are muted.

Now for all incoming notifications the isDismissed flag is set by default.

add

Type: (notifications: Notification[]) => void

Adds a new notification to the notification store and displays it.

@param:

notifications - the notifications to add

@see:

@see:

@example:

Display a notification on button press

function NotificationGenerator() {
	const add = useNotifications(state => state.add);

	const notification: Notification = {
		type: 'INFO',
		message: 'Button pressed',
		description: 'Someone pressed the button',
		isDismissed: false
	};

	return <button onClick={() => add(notification)}>New notification</button>;
}
dismiss

Type: (notifications: Notification[]) => void

Dismisses a notification in the notification store.

@param:

notifications - the notifications to dismiss

@see:

@see:

@see:

@example:

Log all new notifications

function useNotificationLogger() {
	const { notifications, dismiss } = useNotifications(state => ({
	  notifications: state.notifications,
		dismiss: state.dismiss
	}));

	useEffect(() => {
		// filter out all new notifications
		const new = notifications.filter(notification => !notification.isDismissed);
		// log them
		new.forEach(notification => {
			console.log(`${notification.message}: ${notification.description}`);
		});
		// and dismiss them to not log them again
		dismiss(new);
	}, [notification, dismiss]);
}
showAll

Type: () => void

Reset all dismissed notifications to show them again.

Internally on all stored notifications the isDismissed flag is reset to handle them as "new" notifications.

@see:

@see:

@see:

@example:

Show all notifications button

function ShowAllNotifications() {
	// log all notifications to console
	useNotificationLogger();

	const showAll = useNotifications(state => state.showAll);

	return <button onClick={showAll}>Show all notifications</button>;
}
mute

Type: () => void

Mutes all further notifications.

@see:

@see:

@example:

Mute all incoming notifications

function Mute() {
	const mute = useNotifications(state => state.mute);

	return <button onClick={mute}>Mute</button>;
}
unmute

Type: () => void

Unmutes all further notifications.

@see:

@see:

@example:

Unmute all incoming notifications

function Mute() {
	const unmute = useNotifications(state => state.unmute);

	return <button onClick={unmute}>Unmute</button>;
}
toggle

Type: () => void

Toggles the current mute state to its counter state.

@see:

@see:

@example:

Toggle mute all incoming notifications

function ToggleMute() {
	const toggle = useNotifications(state => state.toggle);

	return <button onClick={toggle}>Toggle mute</button>;
}

ConnectionState

type ConnectionState

Alias for: | 'connected' | 'disconnected' | 'error' | 'noEventBus'

The connection state type of an event bus.

  • Possible states:
  • 'connected' if the eventbus is currently connected to the backend server
  • 'disconnected' if the eventbus is currently disconnected from the backend server
  • 'error' if the eventbus is currently open and an error message was received
  • 'noEventBus' - if currently no event bus exists

EventBusState

interface EventBusState

The event bus state and actions of the Telestion Client Core.

Defines the event bus store and function to open and close an event bus.

Properties

eventBus

Type: EventBus | null

the current eventbus instance if an event bus was opened otherwise it is null

Notice:

Please use the instance object for special purposes only! It can lead to weird bugs tricky to resolve because the object does not change its identity once it is created. React instead is based on detecting changes and only re-renders if a value identity has changed causing differences in ui and app states.

connectionState

Type: ConnectionState

the current connection state of the event bus

error

Type: string | null

optional error message if something gone wrong on connection setup or teardown

lastErrorMessage

Type: ErrorMessage | null

the last received error message through the event bus connection

openEventBus

Type: (serverUrl: string, options?: Options) => void

Creates a new event bus which will automatically connect to the server URL and opens a connection.

@param:

serverUrl - the URL of the backend part to connect to

@param:

options - options to configure the connection of the event bus

@throws:

if openEventBus was called earlier and an eventbus instance already opened

@see:

@see:

@see:

@example:

Open an event bus

const open = useEventBus(state => state.openEventBus);
return (
   <button onClick={() => open('http://localhost:9870/bridge/')}>
       Open event bus
   </button>
);
closeEventBus

Type: () => void

Closes the current event bus and deletes it.

@throws:

if closeEventBus was called earlier and an eventbus instance already closed

@see:

@see:

@see:

@example:

Close an event bus

const close = useEventBus(state => state.closeEventBus);
return <button onClick={() =< close()}>Close event bus</button>;

Authentication

interface Authentication

Current authentication data stored here.

Properties

username

Type: string

the user's name who's is authenticated

authServerUrl

Type: string

the URL of the authentication server

eventBusUrl

Type: string

the URL of the eventbus (returned from the authenticator)

AuthState

interface AuthState

The authentication state and actions of the Telestion Client Core.

Defines the authentication state and functions to change the state.

Properties

auth

Type: Authentication | null

Stores the current authentication state of the application. Contains the username, the authentication and the event bus URL.

If it is null nobody is signed in.

To sign in, call AuthState.signIn. To sign out, call AuthState.signOut.

@see:

@see:

@example:

check authentication status

export function AuthChecker(): ReactNode {
	const auth = useAuth(state => state.auth);

	return auth ? (
		<div>
			<p>User: {auth.username}</p>
			<p>Auth URL: {auth.authServerUrl}</p>
			<p>Event bus URL: {auth.eventBusUrl}</p>
		</div>
	) : <div>Not authenticated</div>;
}

Methods

signIn (...)

function signIn (
   authServerUrl : string ,
   username : string ,
   password : string
) : Promise<SignInResult>

Tries to sign on an authentication server using the specified URL with given user credentials and resolves if the authentication was successful otherwise it rejects if the authentication was not successful.

To log out, call AuthState.signOut.

@param:

authServerUrl - the server to authenticate to

@param:

username - the users name

@param:

password - the users password

@see:

@see:

@example:

simple sign in process

import shallow from 'zustand/shallow';

// function component context
const { user, signIn } = useAuth(state => ({
	user: state.user,
	signIn: state.signIn
}), shallow);

const signIn = () => {
	if (!user) {
		signIn('http://localhost:9870/bridge', 'alice', '12345')
			.then(signInRes => {
				console.log(`User ${signInRes.user} signed in`);
			})
			.catch(err => {
				console.log(`Cannot log in because: ${err.message}`);
			});
	}
};
signOut (...)

function signOut ( ) : Promise<SignOutResult>

Tries to sign out from the logged in authentication server and close all connections.

To log in again, call AuthState.signIn.

@see:

@see:

@example:

simple sign out process

import shallow from 'zustand/shallow';

// function component context
const { user, signOut } = useAuth(state => ({
	user: state.user,
	signOut: state.signOut
}), shallow);

const signOut = () => {
	if (user) {
		signOut()
			.then(()) => {
				console.log(`Logged out`);
			})
			.catch(err => {
				console.log(`Cannot log out because: ${err.message}`);
			});
	}
};

useLogger (...)

function useLogger (
   system : string
) : ReturnType<typeof getLogger>

Returns a component logger for a specific system.

In the background it uses logsemts. For a better understanding, please take a look at their [https://github.com/fliegwerk/logsemts | GitHub page](#https://github.com/fliegwerk/logsemts | GitHub page).

@param:

system - the system or component the logger is for

@returns:

the component logger for the specified system

@see:

@see:

@example:

export function MyComponent(): ReactNode {
	const logger = useLogger('My Component');

	return (
		<button onClick={() => logger.info('Button clicked')}>
			Click Me!
		</button>;
}

getLogger (...)

function getLogger (
   system : string
) : ComponentLogger

Builds and returns a component logger for a specific system.

@param:

system - the system or component the logger is for

@returns:

the component logger for the specified system

@example:

const logger = getLogger('My Component');

logger.log('I am a log message');
logger.success('I am a success message');
logger.warn('I am a warning message');