Niall Lonergan
Niall Lonergan

Reputation: 901

Using constructor items within a function-based component

I'm following along to this PubNub Push Notifications in React-JS tutorial and everything is going fine up until I add the Constructor to the code as it states in the tutorial. I (think I) know enough about react to know that you cannot use a constructor in a non-class based component.

I can't seem to figure out how I would implement this. It appears that when the tutorial was made, the boilerplate code has since been updated and this constructor is no longer supposed to be used in this way.

Below is an image of where I am with the code and in the tutorial:

Image of the function

Should I just convert this to a class-based component? or will that limit me from using hooks in the future?

(Apologies for lack of react knowledge)

Upvotes: 0

Views: 191

Answers (1)

Andrii Golubenko
Andrii Golubenko

Reputation: 5179

You need to use useRef and useEffect hooks:

Why useRef?

The useRef() Hook isn’t just for DOM refs. The “ref” object is a generic container whose current property is mutable and can hold any value, similar to an instance property on a class. more

this.pubnub is an instance property of a class, so you have to add it to useRef hook.

Why useEffect?

useEffect, adds the ability to perform side effects from a function component more

Initialization of PubNubReact - is a side effect, so you need to add it to useEffect hook.

UPDATE

Bad news: It looks like that pubnub-react can't be used with functional components, they have very weird API and they even agree with this (You could read about that in this issue)

Good news: You could use an official pubnub package in your application and it will work great:

import React, { useRef, useEffect } from 'react';
import PubNub from 'pubnub';

function App() {
  const pubnub = useRef(null);

  useEffect(() => {
    pubnub.current = new PubNub({...});

    pubnub.current.addListener({
      message(msg) { console.log(msg) }
    });

    pubnub.current.subscribe({ channels: ['channel1'] });

    pubnub.current.publish({ message: 'hello world from react', channel: 'channel1' });
  }, []);

  return (...);
}

Upvotes: 4

Related Questions