Search session
This page includes reference documentation for the SearchSession class in the Mapbox Search JS Core framework.
SearchSession
A SearchSession object is a managed entrypoint to the Mapbox Search Box API
or Mapbox Address Autofill API.
SearchSession abstracts the suggest/retrieve flow of the two-step interactive search experience.
Compared to using these APIs directly, you can use a SearchSession to:
- Automatically manage the session token lifecycle.
- Debounce calls to SearchSession#suggest.
- Abort in-flight requests with an imperative API.
Parameters
| Name | Description |
|---|---|
| The search interface to wrap. | |
| The time in milliseconds to wait before sending a new request to the SearchSession#suggest call. |
Example
const search = new SearchBoxCore({ accessToken: 'pk.my-mapbox-access-token' });
const session = new SearchSession(search);
session.addEventListener('suggest', (res) => {
presentResultsToUser(res.suggestions);
});
session.addEventListener('retrieve', (res) => {
doSomethingWithFeatureCollection(res);
});
document.querySelector('button').addEventListener('click', (event) => {
const suggestions = session.suggestions?.suggestions;
if (!suggestions || !suggestions.length) {
return;
}
const suggestion = suggestions[0];
if (session.canRetrieve(suggestion)) {
session.retrieve(suggestion);
} else if (session.canSuggest(suggestion)) {
// .. go through suggest flow again ..
session.suggest(suggestion.text);
}
});
session.suggest('Washington D.C.');
Instance Members
Methods
SessionToken
A SessionToken object is a unique identifier that groups together suggest / retrieve calls as part of the
Mapbox Search Box API.
Session tokens are used for billing and customer-accessible analytics.
Calling SessionToken will return an id with a UUIDv4 value. If you want to manage the token id yourself, you
can pass your value into SessionToken (a UUIDv4 value is recommended).
Any method that accepts a SessionToken object as an argument or option
can also accept a unique string and will perform an implicit conversion.
This flexible type is documented as SessionTokenLike.
Note that when using the SearchSession class, the SessionToken is automatically managed by SearchSession.
Example
const token = new SessionToken();
console.log(token.id); // = I am a UUIDv4 value!
Static Members
Instance Members
SessionTokenLike
A SessionToken object or string representing a Mapbox Search Box API session token.
It's recommended this value is a UUIDv4 value.
(SessionToken | string)Example
const v1 = new SessionToken();
const v2 = new SessionToken('f06e7531-6373-4d5a-8614-b6f313488050');
const v3 = 'f06e7531-6373-4d5a-8614-b6f313488050';
Evented
Evented mixes methods into other classes for event capabilities.
If you are an end-user, you will most likely use these methods through classes like SearchSession.
For lists of events you can listen for, see API documentation for specific classes.