Accessing Data with Context
Sometimes you need to store arbitrary data so you can access it later in your autocomplete. For example, when retrieving hits from Algolia, you may want to reuse the total number of retrieved hits in a template.
Autocomplete lets you store data using its Context API and access it anywhere from the state.
Usage
Context exposes a setContext
function, which takes an object and merges it with the existing context. You can then access the context in state.context
.
The following example stores the number of hits from an Algolia response, making it accessible everywhere in your autocomplete.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
autocomplete({
// ...
getSources({ query, setContext }) {
return getAlgoliaResults({
searchClient,
queries: [
{
indexName: 'instant_search',
query,
},
],
transformResponse({ results, hits }) {
setContext({
nbProducts: results[0].nbHits,
});
// You can now use `state.context.nbProducts`
// anywhere where you have access to `state`.
return hits;
},
});
},
});
Context can be handy when developing Autocomplete plugins. It avoids polluting the global namespace while still being able to pass data around across different lifecycle hooks.
1
2
3
4
5
6
7
8
9
10
11
12
function createAutocompletePlugin() {
return {
// ...
subscribe({ setContext }) {
setContext({
autocompletePlugin: {
// ...
},
});
},
};
}
Reference
The setContext
function is accessible on your autocomplete
instance.
It’s also provided in:
getSources
onSubmit
onReset
source.onActive
source.onSelect
source.getItems
plugin.subscribe
The context
object is available on the state
object.
setContext
|
type: (value: Record<string, unknown>) => void
The function to pass data to store it in the context. |
context
|
type: Record<string, unknown>
The context to read data from. |