3

I need to fetch integrations info in JSON format and I need help converting useRef (functional component) to createRef(class component). Functional component:

import { createTTNCClient } from '~/shared/clients/ttnc';

const DevicesTable: React.FC<Props> = (props) => {
        const TTNCClient = useRef(createTTNCClient());
          const fetchIntegrations = async (): Promise<Integration[]> => {
        try {
          const resp = await TTNCClient.current.getIntegrations();      
          return resp.data.content;
        } catch (err) {
          throw new Error(err);
        }
      };
    }

I tried to make a Class component:

export class DevicesTable extends React.PureComponent<Props> {
  private TTNCClientRef: React.RefObject<any>;

  constructor(props) {
    super(props);
    this.TTNCClientRef = React.createRef();
  }
render() {
   const TTNCClient = this.TTNCClientRef.current.getIntegrations(); 
     
    const fetchIntegrations = async (): Promise<Integration[]> => {
      try {
        const resp = await TTNCClient;
        console.log(resp.data.content)
        return resp.data.content;
        } catch (err) {
        throw new Error(err);
        }
    };
 }
   return (
   <div></div>
 )
}

But it throws error regarding function getIntegrations(). I guess because I didn't add 'createTTNCClient' in the class component. Here how it looks with functional component:

const TTNCClient = useRef(createTTNCClient());

but I don't know how to add 'createTTNCClient()' to 'createRef' in a class component.

Daria
  • 83
  • 1
  • 8
  • Since `useRef` is a hook it can only be used inside a function component. Why not use `createRef`? https://reactjs.org/docs/refs-and-the-dom.html – evolutionxbox Mar 01 '22 at 09:13
  • Your class component code doesn't appear to call the `createTTNCClient` constructor. – Drew Reese Mar 01 '22 at 09:13
  • Your code snippets don't appear to be complete and reproducible code. Where is `fetchIntegrations` function called? Can you share more complete code? I'm 100% certain you don't want that logic in your `render` method as it's a pure, synchronous function. https://stackoverflow.com/help/minimal-reproducible-example – Drew Reese Mar 01 '22 at 09:19

1 Answers1

3

Your class component code doesn't appear to call the createTTNCClient constructor.

You could probably do it there in the class constructor:

constructor(props) {
  super(props);
  this.TTNCClientRef = React.createRef();

  this.TTNCClientRef.current = createTTNCClient();
}

Or in the componentDidMount lifecycle method:

componentDidMount() {
  this.TTNCClientRef.current = createTTNCClient();
}

And as a precaution, apply some null-checks when attempting to invoke:

const TTNCClient = this.TTNCClientRef.current?.getIntegrations();
Drew Reese
  • 165,259
  • 14
  • 153
  • 181