0

I am unsuccessfully trying to initialise and use a service class from a React hook. The service class looks like:

export class ExampleService {
  constructor(private exampleParams: string[]) {}

  isPresent(exampleName: string): boolean {
    return this.exampleParams.includes(exampleName);
  }

  getAll(): string[] {
    return this.exampleParams;
  }

  setExamples(exampleParams: string[]): void {
    this.exampleParams = exampleParams;
  }
}

And then in the hook I am trying to use this class:

import { ExampleService } from '../somewhere/example-service';
import { useContext } from 'react';

import { ExampleContext } from '../contexts/example-context';

export const useExample = () => {
  const { currentExamples } = useContext(ExampleContext);
  const checkExamples = new ExampleService(currentExamples);

  return [checkExamples.isPresent];
};

However, I am getting TypeError: Cannot read property 'exampleParams' of undefined when I try to test the code :/ (The error is on isPresent function above).

What am I doing wrong?

Shlomi Zadok
  • 278
  • 4
  • 10
  • 1
    what is the value of `currentExamples` after you are getting from `useContext(ExampleContext)`? – DecPK Jul 03 '22 at 06:21
  • `currentExamples` I'd be getting from `useContext(ExampleContext)` is an array of strings `['example-1', 'example-2']` – Shlomi Zadok Jul 03 '22 at 06:24
  • 1
    How are you using your `useExample` hook? The functon you return within your array is going to be unbound, so calling it won't have `this` set to `checkExamples` unless you explicitly do so. You need something like `[checkExamples.isPresent.bind(checkExamples)]` or `[(...args) => checkExamples.isPresent(...args)]` – Nick Parsons Jul 03 '22 at 06:24
  • You should add [minimal reproducible code](https://stackoverflow.com/help/minimal-reproducible-example). You can also use codesandbox where you can make your code runnable – DecPK Jul 03 '22 at 06:27
  • 1
    `[checkExamples.isPresent.bind(checkExamples)]` did the work! Thank you so much @NickParsons ❤️ – Shlomi Zadok Jul 03 '22 at 06:33

0 Answers0