Cloud React Hooks
useCloud()
Access the currently-scoped cloud client from the React context.
function App() {
const cloud = useCloud('msg');
const msg = cloud.get('msg');
useEffect(() => {
msg.put('Hello, world!');
});
useCloudValue(docName)
Subscribe the component to a document or the value of a block. Re-render if the value ever changes.
function DisplayMessage() {
const message = useCloudValue('msg');
return <Text>{message}</Text>;
}
In the above example, "message" will be undefined while the doc loads. Once loaded, it may say "hello world", as defined by the "msg" doc. When it changes, the component will re-render.
useCloudValue(doc)
If you have access to the client doc object, you can pass it directly:
function DisplayMessage() {
const cloud = useCloud();
const messageDoc = cloud.get('msg');
const message = useCloudValue(messageDoc);
return <Text>{message}</Text>;
}
useCloudValue(block)
You can also pass a client block, if you want to observe an immutable value. This is handy because a block value may not be loaded yet, and useCloudValue will trigger loading and cause your component to re-render once it loads.
function DisplayMessage({ versionBlockId }) {
const cloud = useCloud();
const messageDoc = cloud.get('msg');
const messageAtVersion = messageDoc.getBlock(versionBlockId);
const message = useCloudValue(messageAtVersion);
return <Text>{message}</Text>;
}
useCloudState
Like React's "useState" hook, except the state is saved on the source.
const [state, setState] = useCloudState('StateName', {});
Provide the doc name and initial state to `useCloudState`
useCloudReducer
Like React's "useReducer" hook, except the reducer may also run on the back-end.
const [tasks, dispatch] = useCloudReducer(
'TaskActions', // Name of the action chain doc
'TaskReducer', // Name of the reducer (which should match on the server)
TaskReducer, // regular reducer
[] // initial state
);
To configure the server, you currently need to set up an eval source with the same reducer:
const source = createEvalSource({
source: storageSource,
domain: 'todo.aven.io',
evalDocs: {
TaskReducer: createReducerLambda('TaskReducer', TaskReducer, []),
},
});