useTablesState
The useTablesState hook returns a Tables object and a function to set it, following the same pattern as React's useState hook.
useTablesState(storeOrStoreId?: StoreOrStoreId): [Tables, (tables: Tables) => void]| Type | Description | |
|---|---|---|
storeOrStoreId? | StoreOrStoreId | The |
| returns | [Tables, (tables: Tables) => void] | An array containing the |
This is a convenience hook that combines the useTables and useSetTablesCallback hooks. It's useful when you need both read and write access to all Tables in a single component.
A Provider component is used to wrap part of an application in a context, and it can contain a default Store or a set of Store objects named by Id. The useTablesState hook lets you indicate which Store to use: omit the parameter for the default context Store, provide an Id for a named context Store, or provide a Store explicitly by reference.
Example
This example creates a Store outside the application, which is used in the useTablesState hook by reference. A button updates the Tables when clicked.
import {createStore} from 'tinybase';
import React from 'react';
import {createRoot} from 'react-dom/client';
import {useTablesState} from 'tinybase/ui-react';
const store = createStore().setTables({pets: {fido: {species: 'dog'}}});
const App = () => {
const [tables, setTables] = useTablesState(store);
return (
<div>
{JSON.stringify(tables)}
<button
onClick={() => setTables({...tables, species: {dog: {price: 5}}})}
>
Add
</button>
</div>
);
};
const app = document.createElement('div');
const root = createRoot(app);
root.render(<App />);
console.log(app.innerHTML);
// -> '<div>{"pets":{"fido":{"species":"dog"}}}<button>Add</button></div>'
const _button = app.querySelector('button');
// -> _button MouseEvent('click', {bubbles: true})
console.log(app.innerHTML);
// ->
`
<div>
{"pets":{"fido":{"species":"dog"}},"species":{"dog":{"price":5}}}
<button>Add</button>
</div>
`;
Since
v7.3.0