usePuck
A hook for building custom components that can interact with Puck.
import { Puck, usePuck } from "@measured/puck";
const JSONRenderer = () => {
const { appState } = usePuck();
return <div>{JSON.stringify(appState.data)}</div>;
};
export function Editor() {
return (
<Puck>
<JSONRenderer />
</Puck>
);
}Components using the usePuck hook must be rendered within the <Puck> context as children, overrides or plugins.
Returns
| Param | Example | Type |
|---|---|---|
appState | { data: {}, ui: {} } | AppState |
dispatch | (action: PuckAction) => void | Function |
history | {} | Object |
selectedItem | { type: "Heading", props: {id: "my-heading"} } | ComponentData |
setHistories | setHistories: (histories) => {} | Function |
setHistoryIndex | setHistoryIndex: (index) => {} | Function |
appState
The current application state for this Puck instance.
console.log(appState.data);
// { content: [], root: {}, zones: {} }dispatch
Execute an action to mutate the Puck application state.
dispatch({
type: "setUi",
ui: {
leftSideBarVisible: false,
},
});history
The history API provides programmatic access to the undo/redo AppState history.
| Param | Example | Type |
|---|---|---|
back | () => void | Function |
forward | () => void | Function |
hasPast | true | Boolean |
hasFuture | false | Boolean |
histories | [{ id: 'abc123', data: {} }] | History[] |
index | 5 | Number |
history.back
A function to move the app state back through the histories.
history.forward
A function to move the app state forward through the histories.
history.hasPast
A boolean describing whether or not the present app state has past history items.
history.hasFuture
A boolean describing whether or not the present app state has future history items.
history.histories
An array describing the recorded history as History objects.
History params
| Param | Example | Type |
|---|---|---|
data | {} | AppState |
id | abc123 | String |
data
The app state payload for this history entry.
id
An optional ID for this history entry.
history.index
The index of the currently selected history in history.histories
selectedItem
The currently selected item, as defined by appState.ui.itemSelector.
console.log(selectedItem);
// { type: "Heading", props: {id: "my-heading"} }setHistories
A function to set the history state.
const { setHistories } = usePuck();
setHistories([]); // clears all historysetHistoryIndex
A function to set current history index.
const { setHistoryIndex } = usePuck();
setHistoryIndex(2);