pusher / pusher-js

Pusher Javascript library
http://pusher.com
MIT License
2.11k stars 374 forks source link

BUG - Error: Connection closed. (active status - Code With Antonio) #778

Open nicitaacom opened 1 year ago

nicitaacom commented 1 year ago

I got a bug by using pusher

I want to create 'Active' 'Inavtive' functionality When user active (on site) - I see 'Active' when user closed site I see 'Inactive'

Lets me know how you understood what I want

Note

This issue may be converted to discussion but I'm still think that it something with pusher because previouly it worked without errors For example here with pages directory - https://github.com/nicitaacom/17_messenger-clone

The issue is I always get 'Inactive' (false) or error 'Connection closed' in my console

If you did similar functionalify - please send github repository For me codesandbox doesn't work (I create minimal example and then when I leave page and open codesandbox again it doesn't opens) - other platforms are terrible becasue no 'open in VS code' button

Now I have in 'app/api/pusher/auth.ts' this code (tried with 'pages/api/pusher/auth.ts' - I got error about cookies

import { NextApiRequest, NextApiResponse } from "next"

import { pusherServer } from "@/libs/pusher"
import supabaseServer from "@/libs/supabaseServer"
import { getCookie } from "@/utils/helpersSSR"

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
  const session = await supabaseServer().auth.getSession()

  const userId =
    session.data.session?.user.id === undefined ? getCookie("anonymousId")?.value : session.data.session?.user.id

  const socketId = req.body.socket_id
  const channel = req.body.channel_name
  const data = {
    user_id: userId!,
  }

  const authResponse = pusherServer.authorizeChannel(socketId, channel, data)

  return res.send(authResponse)
}

I have this store with zustand

import { create } from "zustand"

interface ActiveListStore {
  members: string[]
  add: (id: string) => void
  remove: (id: string) => void
  set: (ids: string[]) => void
}

const useActiveList = create<ActiveListStore>()(set => ({
  members: [],
  add: id => set(state => ({ members: [...state.members, id] })),
  remove: id => set(state => ({ members: state.members.filter(memberId => memberId !== id) })),
  set: ids => set({ members: ids }),
}))

export default useActiveList

And I have this hook useActiveChannel

import { useEffect, useState } from "react"
import { Channel, Members } from "pusher-js"

import useActiveList from "../../store/ui/useActiveList"
import { pusherClient } from "@/libs/pusher"

const useActiveChannel = () => {
  const { set, add, remove } = useActiveList()

  const [activeChannel, setActiveChannel] = useState<Channel | null>()

  useEffect(() => {
    let channel = activeChannel

    if (!channel) {
      channel = pusherClient.subscribe("presence-tickets")
      setActiveChannel(channel)
    }

    channel.bind("pusher:subscription_succeeded", (members: Members) => {
      const initialMembers: string[] = []

      members.each((member: Record<string, any>) => initialMembers.push(member.id))
      set(initialMembers)
    })

    channel.bind("pusher:member_added", (member: Record<string, any>) => {
      add(member.id)
    })

    channel.bind("pusher:member_remove", (member: Record<string, any>) => {
      remove(member.id)
    })

    return () => {
      if (activeChannel) {
        pusherClient.unsubscribe("presence-tickets")
        setActiveChannel(null)
      }
    }
  }, [activeChannel, set, add, remove])
}

export default useActiveChannel

In MessagesHeader I want to show active status but it always 'Inactive' (false)

interface MobileSidebarProps {
  owner_username: string
  owner_avatar_url: string
  owner_id: string
}

export function MessagesHeader({ owner_username, owner_avatar_url, owner_id }: MobileSidebarProps) {
  const { avatar_url } = useSender(owner_avatar_url, owner_id)
  const { members } = useActiveList()
  const isActive = members.indexOf(owner_id) !== -1
  console.log(20, "members - ", members)

  return (
 <p className={twMerge(`text-xs`, isActive && "text-success")}>{isActive ? "Active" : "Inactive"}</p>
)
benw-pusher commented 1 year ago

I can't review your example site as it appears to require login - are you able to share a public example?

nicitaacom commented 1 year ago

I can't review your example site as it appears to require login - are you able to share a public example?

Sure here it is - https://github.com/nicitaacom/acc2-pusher_active_status

benw-pusher commented 11 months ago

When running the app you shared I get a different error -

⨯ app/page.tsx (10:10) @ Home
 ⨯ Error: no userId found in page.tsx
    at Home (./app/page.tsx:17:15)
    at stringify (<anonymous>)
   8 |
   9 |   if (!userId) {
> 10 |     throw new Error("no userId found in page.tsx")
     |          ^
  11 |   }
  12 |
  13 |   return (

Are you able to add logging to your code, or enable Pusher.LogToConsole = true to show Pusher logs?

nicitaacom commented 11 months ago

When running the app you shared I get a different error -

Are you able to add logging to your code, or enable Pusher.LogToConsole = true to show Pusher logs?

I got no error when I pnpm dev in terminal

This project has really bad docs image

Where I should write this?

image

benw-pusher commented 11 months ago

This should be specified in any file you import the pusher-js library. So In this case in the app/libs/pusher.ts. You may need to change the import statement to import Pusher from 'pusher-js';

I got no error when I pnpm dev in terminal

I also get no error when I run the terminal command, but when visiting localhost:3000 as the terminal output suggests I get the error I shared.

nicitaacom commented 11 months ago

Thank you for your answer - how you looking to call up in discrod and solve this problem much quicker? I'm free from 10:00 till 20:00 CET

Muhammad1230 commented 11 months ago

Dear pusher/pusher-js,

This is a confirmation that we received your email and registered it as ticket #725487099. You can always reply to this email if you want to add additional information.

Kinds regards,

Team YukTam -M-U

nicitaacom commented 11 months ago

https://github.com/pusher/pusher-js/assets/39565703/d4f26054-2fa7-429c-a30a-e1e042a4f8cb

Muhammad1230 commented 11 months ago

Dear pusher/pusher-js,

This is a confirmation that we received your email and registered it as ticket #725487576. You can always reply to this email if you want to add additional information.

Kinds regards,

Team YukTam -M-U

nicitaacom commented 11 months ago

When import Pusher from 'pusher-js'; and Pusher.logToConsole = true

I got this image

Muhammad1230 commented 11 months ago

Dear pusher/pusher-js,

This is a confirmation that we received your email and registered it as ticket #725487890. You can always reply to this email if you want to add additional information.

Kinds regards,

Team YukTam -M-U

benw-pusher commented 11 months ago

The internal server error from your video is coming from your auth process (the error shows auth.1 as the originator of the error), you may need to add logging to identify why this is. Clicking the auth.1 in the browser console will even take you to the file that is causing the 500 error.

nicitaacom commented 11 months ago

Clicking the auth.1

What? auth.1? where?

Also this answer don't solve problem cause I see nothing to do from my side to fix that

If you know how to fix it it would be nice when you provide YouTube video like where you fix it in my repositoty I created as minimal example or we can talk in discord

If you don't want to help just let me know If you want to help somehow just send YouTube video link or time when you are free to talk and your discord

benw-pusher commented 11 months ago

Your replication environment didn't work so I can't share a video.

The auth.1 is shown in the browser debug console, on the right of the error.

nicitaacom commented 11 months ago

Your replication environment didn't work so I can't share a video.

The auth.1 is shown in the browser debug console, on the right of the error.

ok and how it help me to fix this issue?

benw-pusher commented 10 months ago

As before, you may need to add logging to the auth process so you can see what the precise issue is and why it is being thrown