Daria
Daria

Reputation: 83

How can I rewrite useRef with class component?

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.

Upvotes: 3

Views: 2692

Answers (1)

Drew Reese
Drew Reese

Reputation: 202605

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();

Upvotes: 3

Related Questions