new ReactHooks()
The BrainClient.ReactHooks
namespace has several utility hooks that make integrating
BrainClient into React apps easy without requiring you to attach event listeners
or handle async responses directly in your functional rendering component.
Example usage:
function BrainSecondTicker({ ipAddress }) {
// getBrainClient does not need a hook because it is not async and always
// returns same client for the same ipAddress
const bc = BrainClient.getBrainClient(ipAddress);
const sysDevice = BrainClient.ReactHooks.useDevice(bc, 'System Device');
const secondState = BrainClient.ReactHooks.useDeviceState(sysDevice, 'SECOND_STATE');
// Render the state as JSX
// This will automatically re-render whenever
// the Brain sends a new value for the state
return (<>
Current Seconds on {ipAddress}: <b>{secondState.normalizedValue}</b>
</>);
}
Methods
(static) useConnectionStatus(brainClient):string
Get a React state variable containing current state value from BrainClient.CONNECTION for the given BrainClient.
Event listeners are attached in a React.useEffect
hook to automatically attach/unattach
from the BrainClient.EVENTS.CONNECTION_STATUS_CHANGED
event and automatically update the
variable returned from this hook with the new status whenever the status changes.
Related: See BrainClient#getConnectionStatus and BrainClient.CONNECTION for documentation on the various possible connection states.
Parameters
Returns
- Type
- :string
One of the connection state strings described in BrainClient.CONNECTION indicating the current connection state of the given BrainClient. Related, see BrainClient#getConnectionStatus.
(static) useDevice(client, deviceNameOrId):BrainDevice
Provides a React Hook to retrieve a device from the Brain given the device Name or ID
Parameters
Client to use to access devices
Name or ID of the device to retrieve
Returns
- Type
- :BrainDevice
Returned value will eventually be set to BrainDevice object
(static) useDeviceState(device, stateNameOrId):object
Get a specific state from the device. This method will automatically attach a listener to the BrainDevice.STATE_CHANGED
event and automatically update the returned value whenever a new state value is received from the brain.
Uses React.useEffect
internally to attach/remove event listener for that event so event listener is removed when
component unmounts.
See BrainDevice#getState for more documentation on this result.
Parameters
Device to get the commands from
Name or ID of state to retrieve and watch
Returns
- Type
- :object
State information object, see BrainDevice#getState for more documentation on this result.