Context (Recommendation Engine)

This is for:

Developer

Example Implementation

context.ts

import {buildContext} from '@coveo/headless';
import {useContext} from 'react';
import {AppContext} from '../../context/engine';
 
export function Context() {
  const {engine} = useContext(AppContext);
  const ctx = buildContext(engine!);
 
  ctx.set({ageGroup: '30-45', interests: ['sports', 'camping', 'electronics']});
 
  return null;
}

The Context controller injects custom contextual information into the search requests and usage analytics search events sent from a search interface.

Example: context.ts

Methods

add

Adds (or, if one is already present, replaces) a new context key-value pair.

Parameters

  • contextKey: string

    The context key to add.

  • contextValue: string | string[]

    The context value to add.

remove

Removes a context key from the query.

Parameters

  • key: string

    The context key to remove.

set

Sets the context for the query. This replaces any existing context with the new one.

Parameters

  • context: Record<string, ContextValue>

    The context to set for the query.

subscribe

Adds a callback that’s invoked on state change.

Parameters

  • listener: () => void

    A callback that’s invoked on state change.

Returns Unsubscribe: A function to remove the listener.

Attributes

state

The state of the Context controller.

Properties

  • values: Record<string, ContextValue>

    An object holding the context keys and their values.

Initialize

buildContext

Creates a Context controller instance.

Parameters

  • engine: CoreEngine

    The headless engine.

  • props: ContextProps

    The configurable Context controller properties.

Returns Context

ContextProps

The configurable Context controller properties.

Properties

  • initialState?: ContextInitialState

    Represents the initial state of the context. If provided, it should adhere to the structure defined by the ContextInitialState interface.

ContextInitialState

Represents the initial state of the context. If provided, it should adhere to the structure defined by the ContextInitialState interface.

Properties

  • values: Record<string, ContextValue>

    Represents the initial key/value pair of the context.

Unsubscribe

Call signatures

  • (): void;