useCellState
The useCellState hook returns a Cell from a Store and a callback to set it, following the common React useState convention.
useCellState(
tableId: string,
rowId: string,
cellId: string,
storeOrStoreId?: StoreOrStoreId,
): [CellOrUndefined, (cell: Cell) => void]| Type | Description | |
|---|---|---|
tableId | string | |
rowId | string | |
cellId | string | |
storeOrStoreId? | StoreOrStoreId | The |
| returns | [CellOrUndefined, (cell: Cell) => void] | A tuple containing the current |
This hook is useful for creating components that read and write a Cell in a single line, similar to how you would use React's useState hook.
The component this is used in will re-render when the Cell changes.
Example
This example creates a Store outside the application, which is used in the useCellState hook by reference.
import {createRoot} from 'react-dom/client';
import {createStore} from 'tinybase';
import React from 'react';
import {useCellState} from 'tinybase/ui-react';
const store = createStore().setCell('pets', 'fido', 'visits', 0);
const App = () => {
const [visits, setVisits] = useCellState(
'pets',
'fido',
'visits',
store,
);
return (
<span>
Visits: {visits}
<button onClick={() => setVisits(visits + 1)}>Visit</button>
</span>
);
};
const app = document.createElement('div');
const root = createRoot(app);
root.render(<App />);
console.log(app.innerHTML);
// -> '<span>Visits: 0<button>Visit</button></span>'
const _button = app.querySelector('button');
// -> _button MouseEvent('click', {bubbles: true})
console.log(app.innerHTML);
// -> '<span>Visits: 1<button>Visit</button></span>'
root.unmount();
Since
v7.3.0