Available React Hooks#
This page describes the React hooks available for use.
.. note:: The following React hooks are available under the Hooks object for use, e.g. Hooks.useCollection.
useCollection#
useCollection(collection, isEmpty, serializer, additionalDeps)
This hook attaches a Backbone collection to a React state and returns a serialized collection object together with loading and isError collection states.
Arguments:
Collection - Backbone collection object
isEmpty - Custom function that will determine if the collection is empty. Most of the time you can just check if
collection.length === 0, but sometimes you may need to do additional things depending on the use case.Serializer - Optional serializer function. If it’s not passed collection will be serialized with
collection.toJSON()additionalDeps - Additional
useEffectdependencies that will trigger collection refetch on change. By default, the only dependency is the dashboard state object, but you can pass additional ones if needed.
useCollectionRecreate#
useCollectionRecreate = (getCollection, props, config)
This hook recreates a collection based on a change in the parameters.
Arguments:
GetCollection: Function to get a collection with parameters.
WidgetProps: An object representing widget properties to be passed down.
Config: An object representing widget config to be passed down.
useWidgetCollection#
useWidgetCollection(widgetProps, collection, isEmpty, serializer, additionalDeps)
This hook attaches a Backbone collection to a React state and returns an object with all properties needed for a widget. You can use this hook when setting up the main collection for the widget.
It uses the useCollection hook but also adds additional data and structure that helps with passing properties to widget containers and the widgets themselves.
Arguments:
widgetProps - An object representing widget properties to be passed down.
Collection: Backbone collection object
isEmpty: Custom function determining if the collection is empty. Mostly, you can check if
collection.length === 0, though sometimes additional configuration is needed depending on the use case.Serializer: Optional serializer function. If not passed, then collection will be serialized with
collection.toJSON()additionalDeps: Additional
useEffectdependencies that trigger collection refetch on change. By default, the only dependency is the dashboard state object, though you can pass additional ones if needed.
useCommunityTypesCollection#
useCommunityTypesCollection = (props, collection, isEmpty, dashboardSection, serializer)
This hook calls the useWidgetCollection hook and provides a list of additional methods and parameters specific to CommunityTypesCollection.
Additional return parameters:
GetModelById: Function to get a CommunityType by ID.
Total: Number of Community Types.
Arguments:
WidgetProps: An object representing widget properties to be passed down.
Collection: Backbone collection object.
isEmpty: Custom function determining if the collection is empty. Mostly, you can check if
collection.length === 0, though sometimes additional configuration is needed depending on the use case.DashboardSection: The widget section in the Dashboard.
Serializer: Optional serializer function. If not passed, then collection will be serialized with
collection.toJSON().
useCommunityCollection#
useCommunityCollection = (props, collection, isEmpty, dashboardSection, serializer, additionalDeps)
This hook calls the useWidgetCollection hook and provides a list of additional methods and parameters specific to CommunityCollection.
Additional return parameters:
GetModelById: Function to get a Community by ID.
Total: Number of Communities.
LoadNextPage: Function to load the Collection next page (pagination).
Arguments:
WidgetProps: An object representing widget properties to be passed down.
Collection: Backbone collection object
isEmpty: Custom function determining if the collection is empty. Mostly, you can check if
collection.length === 0, though sometimes additional configuration is needed depending on the use case.DashboardSection: The widget section in the Dashboard.
Serializer: Optional serializer function. If not passed, then collection will be serialized with
collection.toJSON().AdditionalDeps: Additional
useEffectdependencies that trigger collection refetch on change. By default, the only dependency is the dashboard state object, though you can pass additional ones if needed.
useCommunitySubscriptionsCollection#
useCommunitySubscriptionsCollection = (props, collection, isEmpty, dashboardSection, serializer)
This hook calls the useWidgetCollection hook and provides a list of additional methods and parameters specific to CommunitySubscriptionsCollection.
Additional return parameters:
GetModelById: Function to get a CommunitySubscription by ID.
Total: Number of CommunitySubscriptions.
LoadNextPage: Function to load the Collection next page (pagination).
Create: Function to create a new CommunitySubscription.
RefetchCollection: Function to refetch the Collection.
BulkCreate: Function to create multiple CommunitySubscriptions.
Arguments:
WidgetProps - An object representing widget properties to be passed down.
Collection - Backbone collection object
isEmpty - Custom function determining if the collection is empty. Mostly, you can check if collection.length === 0, though sometimes additional configuration is needed depending on the use case.
DashboardSection - The widget section in the Dashboard
Serializer - Optional serializer function. If not passed, then collection will be serialized with collection.toJSON()
useContainerDimensions#
useContainerDimensions(ref)
This hook will return the width and the height of an HTML element.
Dimensions are updated on load, on mount/un-mount, when resizing the window, and when the ref changes.
Argument:
Ref: React ref object representing html element. For more information, see the Refs and the DOM reference page.
Example:
const elementRef = React.useRef(null);
const { containerWidth, containerHeight } = useContainerDimensions(carouselRef);
return <SomeComponent ref={elementRef}>
useDashboardState#
useDashboardState(options)
This hook provides a clean, typed API for interacting with the dashboard state store. It is the primary method for managing dashboard selections, queries, facets, time filters, and other dashboard-level state in widgets.
The dashboard state uses Zustand for state management which provides a modern, performant solution for managing complex dashboard interactions.
Arguments#
The hook accepts a single options object with the following properties:
dashboard: Dashboard model available in widget props
dashboardState: Dashboard state instance (Zustand store) available in widget props as well, or can be any custom
dashboardStatestorewidgetModel: Widget configuration model available in widget props
Example:
const selectionsStore = useDashboardState({
dashboard: props.dashboard,
dashboardState: props.dashboardState,
widgetModel: props.widgetModel,
});
Return Value#
The hook returns an object with the following properties and methods:
State Properties#
selections:
IDashboardSelection[]- Array of current dashboard selectionsselectionsQuery:
string- Cached query string built from selectionsglobalSearchMode:
'all' | 'context'- Current search modeid:
string- Unique identifier for this dashboard state instanceinstance:
IDashboardState- Raw Zustand store instance for advanced use
Methods#
Selection Management#
addFacets#
addFacets(facets: [string, string][])
Adds one or more facet-value pairs as dashboard selections.
Arguments:
facets: Array of [facet, value] tuples
Example:
const store = useDashboardState({ dashboard, dashboardState, widgetModel });
// Add single facet
store.addFacets([['source', 'news']]);
// Add multiple facets
store.addFacets([
['category', 'technology'],
['author', 'John Smith']
]);
addSelections#
addSelections(selections: Omit<IDashboardSelection, 'id'>[])
Adds custom selections to the dashboard state. This is useful for adding selections with specific properties like icons, colors, or custom query formats.
Arguments:
selections: Array of selection objects (without id, which is auto-generated)
Example:
store.addSelections([
{
query: 'title:AI',
type: 'FIELD',
widgetId: widgetModel.id,
name: 'AI Topics',
icon: 'search'
}
]);
removeSelections#
removeSelections(selections: IDashboardSelection[])
Removes specific selections from the dashboard state.
Arguments:
selections: Array of selection objects to remove
Example:
// Remove specific selection
const selectionToRemove = store.selections.find(s => s.query === 'test');
if (selectionToRemove) {
store.removeSelections([selectionToRemove]);
}
setSelections#
setSelections(selections: IDashboardSelection[] | (state) => IDashboardSelection[])
Replaces all selections with a new set. Can accept either an array or a function that receives current state.
Arguments:
selections: New selections array or updater function
Example:
// Replace all selections
store.setSelections([
{
id: '1',
query: 'category:news',
type: 'FIELD',
widgetId: widgetModel.id
}
]);
// Use updater function
store.setSelections((currentSelections) =>
currentSelections.filter(s => s.type !== 'TERM')
);
updateSelections#
updateSelections(selectionsToAdd: IDashboardSelection[], selectionsToRemove?: IDashboardSelection[])
Updates selections by adding and/or removing in a single operation.
Arguments:
selectionsToAdd: Selections to add
selectionsToRemove: (Optional) Selections to remove
Example:
store.updateSelections(
[{ query: 'new', type: 'TERM', widgetId: widgetModel.id }],
oldSelections
);
Query Operations#
addQuerySelection#
addQuerySelection(query: string, options?: { clear?: boolean })
Adds a query string as a dashboard selection. The query is parsed into tokens and converted to selection chips.
Arguments:
query: Query string to add
options: (Optional) Object with
clearflag to replace existing query
Example:
// Add to existing query
store.addQuerySelection('artificial intelligence');
// Replace entire query
store.addQuerySelection('machine learning', { clear: true });
getQuery#
getQuery(options?: IGetSearchParamsOptions): string
Returns the combined query string from all selections, dashboard and widget queries.
Arguments:
options: (Optional) Configuration object: -
ignoreGlobalSearch: boolean - Ignore global search mode -includeDisabled: boolean - Include disabled selections - Other options from IGetSearchParamsOptions
Example:
const query = store.getQuery();
const queryWithoutGlobal = store.getQuery({ ignoreGlobalSearch: true });
getSearchParams#
getSearchParams<ContextType>(options?): IApiParams<ContextType>
Returns formatted parameters ready for API calls, including query, facets, time range, etc.
Arguments:
options: (Optional) Same as getQuery options
Example:
const params = store.getSearchParams();
// Returns: { query: '...', query_context: { searchbar_query: '...', dashboard_filters: {...}, ... }, created_after: '...', ... }
getQueryId#
getQueryId(): number
Returns a unique ID for the current query state, useful for cache invalidation.
Example:
const queryId = store.getQueryId();
// Use as cache key
getQueryGlobalSearch#
getQueryGlobalSearch(): string
Returns the global search query string.
Widget-Specific Operations#
updateWidgetSelection#
updateWidgetSelection(selectionsToAdd?, selectionsToRemove?, options?)
Updates selections specific to the current widget. Automatically filters by widget ID.
Arguments:
selectionsToAdd: (Optional) Selections to add for this widget
selectionsToRemove: (Optional) Selections to remove for this widget
options: (Optional) Configuration object with
clearflag
Example:
// Replace widget's selections
store.updateWidgetSelection(
newSelections,
null,
{ clear: true }
);
clearWidgetSelection#
clearWidgetSelection(options?: { widgetId?: string })
Clears all selections created by the current (or specified) widget.
Arguments:
options: (Optional) Object with
widgetIdto clear different widget’s selections
Example:
// Clear current widget's selections
store.clearWidgetSelection();
// Clear specific widget's selections
store.clearWidgetSelection({ widgetId: 'other-widget-id' });
getWidgetSelection#
getWidgetSelection(options?): IDashboardSelection[]
Returns selections created by the current (or specified) widget.
Arguments:
options: (Optional) Object with
widgetIdto get different widget’s selections
Example:
const mySelections = store.getWidgetSelection();
const otherSelections = store.getWidgetSelection({ widgetId: 'other-widget-id' });
Specialized Setters#
setConcept#
setConcept(concept: string | null)
Sets or clears the concept selection.
Arguments:
concept: Concept string or null to clear
Example:
store.setConcept('technology');
store.setConcept(null); // Clear concept
setTime#
setTime(start?, end?, options?)
Sets the time range filter.
Arguments:
start: Start date/time
end: End date/time
options: (Optional) Configuration object
Example:
store.setTime('2024-01-01', '2024-12-31');
store.setTime(null, null); // Clear time filter
setSort#
setSort(field, order, options)
Sets the sort field and order.
Arguments:
field: Field name to sort by
order: Sort order (‘asc’ or ‘desc’)
options: Configuration object
Example:
store.setSort('created_at', 'desc', {});
getTime#
getTime(key: 'start' | 'end')
Gets the start or end time from the current time selection.
Arguments:
key: Either ‘start’ or ‘end’
Example:
const startTime = store.getTime('start');
const endTime = store.getTime('end');
Community Management#
setSelectedCommunity#
setSelectedCommunity(community: ICommunity | null)
Sets or clears the selected community.
Arguments:
community: Community object or null to clear
Example:
store.setSelectedCommunity(communityObj);
store.setSelectedCommunity(null); // Clear
getSelectedCommunityQuery#
getSelectedCommunityQuery(): string
Returns the query string for the selected community.
Example:
const communityQuery = store.getSelectedCommunityQuery();
State Subscriptions#
subscribe#
subscribe(selector, callback, options)
Subscribes to specific state changes using a selector function.
Arguments:
selector: Function to select state slice
callback: Function called when selected state changes
options: (Optional) Subscription options
Example:
useEffect(() => {
// Subscribe to selection changes
const unsubscribe = store.subscribe(
(state) => state.selections, // or any state value, like state.timeSelection or state.globalSearchMode
(value) => { // argument would be a value for which you've subscribed
console.log('State value changed:', value);
}
);
return unsubscribe;
}, []);
Complete Usage Example#
Here’s a complete example showing common dashboard state operations in a widget:
const MyWidget = (props) => {
const store = Hooks.useDashboardState({
dashboard: props.dashboard,
dashboardState: props.dashboardState,
widgetModel: props.widgetModel,
});
// Handle facet click
const handleFacetClick = (facet, value) => {
store.addFacets([[facet, value]]);
};
// Handle search
const handleSearch = (searchText) => {
store.addQuerySelection(searchText);
};
// Clear widget's filters
const handleClear = () => {
store.clearWidgetSelection();
};
// Subscribe to selection changes
React.useEffect(() => {
const unsubscribe = store.subscribe(
(state) => state.selections,
(newSelections) => {
console.log('Dashboard selections updated:', newSelections);
// Refresh widget data
}
);
return unsubscribe;
}, []);
return (
<div>
<button onClick={() => handleFacetClick('category', 'news')}>
Filter by News
</button>
<button onClick={() => handleSearch('artificial intelligence')}>
Search AI
</button>
<button onClick={handleClear}>
Clear Filters
</button>
<div>Current selections: {store.selections.length}</div>
</div>
);
};
Troubleshooting#
Issue: Selections not updating in UI
Solution: Ensure that you’re using the props.dashboardState or Globals.dashboardState when updating selections. Other dashboard widgets are only listening to that state changes.
const store = Hooks.useDashboardState({
dashboard: props.dashboard,
dashboardState: props.dashboardState,
widgetModel: props.widgetModel,
});
// Handle search
const handleSearch = (searchText) => {
store.addQuerySelection(searchText);
};
Issue: Facets not being removed correctly
Solution: Make sure you’re passing the full selection object that matches selection’s query or ID, not just facet/value:
// Find the selection first
const selection = store.selections.find(s => s.query === targetQuery);
store.removeSelections([selection]);
Issue: Widget selections conflicting with dashboard
Solution: Use widget-specific methods:
// Clear only this widget's selections
store.clearWidgetSelection();
// Get only this widget's selections
const mySelections = store.getWidgetSelection();
// Update current widget selection
store.updateWidgetSelection(newSelections, oldSelections);
Additional Resources#
The best documentation is the implementation. If you have any doubts, check the types and actual implementation, which can be found in the following places:
Storybook: Interactive examples of dashboard state usage: https://storybook.squirro.com
Dashboard State Store Implementation:
integration/frontend/userapp/static/js/require/views/react/dashboardState.tsHook Implementation:
integration/frontend/userapp/static/js/require/views/react/hooks.ts
useFacetsCollection#
useFacetsCollection = (props, collection, isEmpty, dashboardSection, serializer)
This hook calls the useWidgetCollection hook and provides a list of additional methods and parameters specific to FacetsCollection.
Additional return parameters:
GetModelById: Function to get a Facet by ID.
Indexed: List of Indexed Facets.
Arguments:
WidgetProps: An object representing widget properties to be passed down.
Collection: Backbone collection object.
isEmpty: Custom function determining if the collection is empty. Mostly, you can check if
collection.length === 0, though sometimes additional configuration is needed depending on the use case.DashboardSection: The widget section in the Dashboard.
Serializer: Optional serializer function. If not passed, then collection will be serialized with
collection.toJSON().
useFeedbackMode#
useFeedbackMode = (dashboard)
This hook tracks the FeedbackMode in a dashboard and returns the boolean representing the current mode and a setFeedbackMode function to change it.
Argument:
Dashboard: Dashboard model, available in all the widgets props.
useItemsCollection#
useItemsCollection = (props, collection, overrides, apiOverrides, dashboardSection,additionalDeps, isEmpty, serializer)
This hook calls the useWidgetCollection hook, attaches additional events, and provides a list of additional methods and parameters specific to ItemsCollection.
Additional return parameters:
LoadNextPage: Function to load the Collection next page (pagination).
ActiveItem: The current active Item.
SetActiveItem: Function to set the active Item.
GetActiveItem: Function to get the active Item.
ActiveEntity: The current active Entity.
SetActiveEntity: Function to set the active Entity.
GetActiveEntity: Function to get the active Entity.
GetExcelUrl: Function to get the Excel URL.
GetModelById: Function to get an Item by ID.
OnEntityClick: Function to be called when an Entity is clicked.
Arguments:
WidgetProps: An object representing widget properties to be passed down.
Collection: Backbone collection object.
Overrides: Object containing all the Widget Component Overrides.
ApiOverrides: Object containing all the Widget API Overrides.
DashboardSection: The widget section in the Dashboard.
isEmpty: Custom function determining if the collection is empty. Mostly, you can check if
collection.length === 0, though sometimes additional configuration is needed depending on the use case.Serializer: Optional serializer function. If not passed, then collection will be serialized with
collection.toJSON().AdditionalDeps - Additional
useEffectdependencies that trigger collection refetch on change. By default, the only dependency is the dashboard state object, though you can pass additional ones if needed.
useQueryEvaluator#
useQueryEvaluator = (additionalQuery, dashboard, user, search)
This hook evaluates the query and attaches events to the Dashboard Store and returns it as a string.
Arguments: 1. AdditionalQuery: Additional widget query as a string. 2. Dashboard: Dashboard model available in all the widget props. 3. User: User model. 4. Search: Search model, available in all the widget props.
useStoreKeyChange#
useStoreKeyChange = (dashboard, storeKey, event)
This hook tracks a store key based on a given event and returns the value.
Arguments:
Dashboard: Dashboard model, available in all the widgets props.
StoreKey: A string representing the store key.
Event: A string representing the event.
useStateWithCallback#
useStateWithCallback = (initialValue)
This hook saves a state value and returns the current value and a function to update the value and use a specified callback function.
Argument:
InitialValue: The initial value of the state, can be of any type.
Example:
const [value, setValueAndCallback] = useStateWithCallback('firstValue');
setValueAndCallback('secondValue', (prevValue, newValue) => console.log(`Previous value: ${prevValue}, New value: ${newValue}`));
useWithoutCollection#
useWithoutCollection = (widgetProps)
This hook acts similarly to useCollection but it doesn’t use a collection. It can be used for widgets without specified collections.
Argument:
WidgetProps: An object representing widget properties to be passed down.
usePrevious#
usePrevious = (value)
This hook tracks the previous value of a given one and returns it.
Argument:
Value: Mutating value of any kind.