The `pubnub removeListener` function does not get triggered when the `useEffect` hook

Operating a single chat works perfectly; however, upon entering and exiting a chat screen before re-entering it, double messaging occurs, and the listener remains active despite being placed in the return of useEffect. I attempted the solution provided in this discussion: React Pubnub Chat. Message duplication or absence of messages

I'm hoping for assistance in pinpointing the issue. Thank you in advance!

 useEffect(() => {
   
    const listener = {
      message: (envelope: any) => {
        if (envelope) {
          const message = {
            channel: envelope.channel,
            message: {
              ...envelope.message,
            },
            uuid: envelope.publisher,
            timetoken: envelope.timetoken,
          }

          dispatch(setMessage(message))
// This log is triggered as many times as you enter and exit the chat due to the listener not being removed
          console.log('Message listener activated!') 
        }

        //   setLastTimeToken(message.timetoken)
      },
    }

    pubnub.addListener(listener)
    pubnub.setUUID(employer._id)


    pubnub.fetchMessages(
      {
        channels: [ch],
        count: 100,
      },
      (status, response) => {
        if (response.channels[ch]) {
          dispatch(setMessages(response?.channels[ch]))
        } else {
          dispatch(setMessages([]))
        }
      },
    )
    pubnub.subscribe({ channels: [ch] })
    
    
    const usersInfo = channel.split('_')
    if (channel !== employer._id && usersInfo[1] !== 'job') {
      const deeberId = usersInfo[0]
      getCandidateById(deeberId).then(res => {
        dispatch(setSelectedChatCandidate(res))
      })
    }
    renderDisplayName()

    return () => {
      pubnub.removeListener(listener) 

      pubnub.unsubscribeAll()
    }

  }, [])

Answer №1

Improved functionality in the PubNub JS SDK resolved a bug leading to repeated callback activation.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Handling scroll events in a functional component using React

I'm having trouble understanding why the onScroll function isn't triggering the console.log statement. <table className="table" onScroll={()=>{console.log("Works")}> The console.log just doesn't seem to be exec ...

The Vue application is encountering an unexpected error in Chrome that is puzzling me as I search for a solution

Currently, I am delving deep into learning Vue.js and have decided to revisit the documentation from scratch and work through it in reverse order. Below is the content of my index.html file: <!DOCTYPE html> <html lang="en"> <hea ...

Material UI Error TS1128: Expected declaration or statement for ButtonUnstyledProps

While working on my application that utilizes Material UI, I encountered an issue. I keep receiving a Typescript error and haven't been able to find a solution for it. TypeScript error in C:/.../node_modules/@mui/base/ButtonUnstyled/index.d.ts(3,1): D ...

Console displays null as the attribute value

When I check the console, I notice that the data-postid attribute is displaying 'null'. What could be causing this issue? I would like to view the data-id in the console when clicking on the button with the id modal-save. I have reviewed my cod ...

"Exploring In-Depth Data Visualization: A Guide to Navigating Charts

It was shocking to me how scarce the information on this subject is. I have a ChartJS pie chart that I would like to delve deeper into by clicking on a slice of the pie. Do you have any suggestions on how to achieve this? ...

Exploring data retrieval from nested arrays of objects in TypeScript/Angular

I have an API that returns an object array like the example below. How can I access the nested array of objects within the JSON data to find the role with roleid = 2 when EmpId is 102 using TypeScript? 0- { EmpId: 101, EmpName:'abc' Role : ...

Exploring Vue 3: Choosing between using import statements in main.js and configuring additionalData in vue.config.js to load a global scss file

I am attempting to load a global SCSS file using the "vue.config.js" file. vue.config.js module.exports = { css: { loaderOptions: { sass: { additionalData: `@import "@/assets/common.scss";` } } } } If I include the style tag in my App. ...

What is the best way to implement an EventHandler class using TypeScript?

I am in the process of migrating my project from JavaScript to TypeScript and encountering an issue with transitioning a class for managing events. To prevent duplicate option descriptions for adding/removing event listeners, we utilize a wrapper like thi ...

Guide to verifying the property value following mocking a function: Dealing with Assertion Errors in Mocha

Based on a recommendation from a discussion on this link, I decided to mock the readFileSync function and then mocked my outer function. Now, my goal is to verify whether the variable's value has been set as expected. file.js const fs1 = require ...

Javascript is not fetching the value

Here is the code snippet I am working with: var categoryDetailId = $("#createEventForm-categoryDetail-idCategory").val(); and this link from my rendered page: After clicking the button, it returns NaN Update: I tried setting it manually, but it still ...

What impact does reselect have on the visual presentation of components?

I'm struggling to grasp how reselect can decrease a component's rendering. Let me illustrate an example without reselect: const getListOfSomething = (state) => ( state.first.list[state.second.activeRecord] ); const mapStateToProps = (state ...

Is there a way to combine all the text on an HTML page into one continuous string without losing the CSS styling?

If I want to change all the text within every HTML element on a page to just the letter "A", how would I do it? Let's say I have a webpage set up like this: <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> ...

Showing a global variable from an external JavaScript library

I have integrated some external libraries into my ionic project. One of these libraries includes the declaration of var loading = false; In my page's .ts file, I am "importing" this variable using: declare var loading; Although I can use this vari ...

Getting the error message "t is not a function. (In 't(i,c)', 't' is an instance of Object)" while attempting to switch from using createStore to configureStore with React Redux Toolkit

I am attempting to switch from react-redux to its alternative react-redux toolkit but I kept encountering this issue t is not a function. (In 't(i,c)', 't' is an instance of Object) and I am unsure of its meaning. Here is the c ...

The type 'undefined' cannot be assigned to type 'Element or null'

One of the components I am using looks like this: const data: any[] = [] <Tiers data={data}/> This is how my component is structured: const Tiers = ({ data, }: { data?: any; }) => { console.log('data', data?.length!); ...

Creating a fresh discord.js v11.3 channel

I've been working on a ticket bot, but I'm encountering issues with my !new command. Can someone please assist me with this problem? I've been referring to Discord's documentation for guidance. Below is the code snippet I'm using: ...

Creating mock implementations using jest in vue applications

I have been experimenting with testing whether a method is invoked in a Vue component when a specific button is clicked. Initially, I found success using the following method: it('should call the methodName when button is triggered', () => { ...

Using React and Typescript: Passing functions as props to other components

In this setup, we have three main components: Toggle, ToggleMenu, and Wrapper. The Toggle component is designed to be universal and used for various functions. The Wrapper component, on the other hand, is meant to change the background color only when the ...

I keep encountering this issue while attempting to retrieve information from an SQL server on a website

Error: There was an issue with the query. The table 'jeanpaulcaruana1bsc5m.tbl_' does not exist. PHP require_once("connection.php"); $connection = connectToMySQL(); $query = "select * from tbl_ members"; $result = mysqli_query($connection, $qu ...

Using Angular2's component templateUrl with a npm package

Seeking advice on the best way to reference templateUrl in a commonly used npm module. I want to avoid including node_modules in the path, as the directory could potentially be renamed. Is there an alternative method that still works effectively? For exam ...