Angular - algolia instantSearch : Cannot read properties of undefined (reading 'range')

610 Views Asked by At

i am trying to connect the basic rangeConnector - copy paste from the docs

https://www.algolia.com/doc/api-reference/widgets/range-input/angular/

but i got : Cannot read properties of undefined (reading 'range')

looks like the state is undefined

code: exactly the same from the docs

wrapper:

<ais-instantsearch [config]="config">
      <app-range-input></app-range-input>
</ais-instantsearch>
import { Component, Inject, forwardRef, Optional } from '@angular/core';
import { TypedBaseWidget, NgAisInstantSearch, NgAisIndex } from 'angular-instantsearch';

import connectRange, { RangeWidgetDescription, RangeConnectorParams } from 'instantsearch.js/es/connectors/range/connectRange';

@Component({
  selector: 'app-range-input',
  template: `
    <div *ngIf="state.range">
      from
      <input type="number" #min [value]="state.start[0]" min="state.range.min" max="state.range.max" />
      to
      <input type="number" #max [value]="state.start[1]" min="state.range.min" max="state.range.max" />
      <button (click)="state.refine([1, 2])">Go</button>
    </div>
  `,
})
export class RangeInputComponent extends TypedBaseWidget<RangeWidgetDescription, RangeConnectorParams> {
  public state: RangeWidgetDescription['renderState']; // Rendering options
  constructor(
    @Inject(forwardRef(() => NgAisIndex))
    @Optional()
    public parentIndex: NgAisIndex,
    @Inject(forwardRef(() => NgAisInstantSearch))
    public instantSearchInstance: NgAisInstantSearch
  ) {
    super('RangeInput');
  }
  ngOnInit() {
    this.createWidget(connectRange, {
      // instance options
      //attribute: 'price',
    });
    super.ngOnInit();
  }
}



1

There are 1 best solutions below

0
Michael K On

It looks like the state object isn't initialized yet and that is your issue here. I tested this out locally and checking if state is truthy before checking the range attribute will allow it to work properly. I slightly modified the code as well to convert the min/max to an integer before sending it to refine() as it was throwing an error there as well.

<div *ngIf="state && state.range">
  from
  <input type="number" #min [value]="state.start[0]" min="state.range.min" max="state.range.max" />
  to
  <input type="number" #max [value]="state.start[1]" min="state.range.min" max="state.range.max" />
  <button (click)="state.refine([this.toInt(min.value), this.toInt(max.value)])">Go</button>
</div>

...

toInt (val: any) {
  return parseInt(val)
}

I'll submit a change request to the documentation to include this change as it can be misleading. Let me know how this works for you! Thanks!