Next.js Discord

Discord Forum

Pusher for Real time advertisement not working

Unanswered
Northeast Congo Lion posted this in #help-forum
Open in Discord
Northeast Congo LionOP
I used pusher to get real time data, like advertisment in queue, not working, got null

import React, { useEffect, useState } from 'react';
import Pusher from 'pusher-js';
import Image from 'next/image';

type Adtype = {
    _id: string;
    link: string;
    image: string;
}

const AdBox = () => {
  const [currentAd, setCurrentAd] = useState<AdType | null>(null);

  useEffect(() => {
    console.log('Adbox pusher api start')
    const pusher = new Pusher(process.env.NEXT_PUBLIC_PUSHER_KEY!, {
      cluster: process.env.NEXT_PUBLIC_PUSHER_CLUSTER!,
      forceTLS: true
    });
    
    console.log('Adbox pusher api middle')
    const channel = pusher.subscribe('ad-channel');
    channel.bind('ad-update', function(data:any) {
      setCurrentAd(data.ad);
    });
    
    return () => {
      pusher.unsubscribe('ad-channel');
    };    
  }, []);
  
  console.log('Adbox pusher:', currentAd)
  return (
    <div>
      {currentAd && (
        <div>
          <Image src={currentAd.image} alt="Advertisement" width={300} height={300} layout="responsive" />
          <a href={currentAd.link} target="_blank" rel="noopener noreferrer">Visit Ad</a>
        </div>
      )}
    </div>
  );
};

export default AdBox;

1 Reply

Northeast Congo LionOP
import {connectDB} from '@/lib/database/mongoose';
import Advertisement from '@/lib/database/models/advertisement.model';
import { NextResponse } from 'next/server';
import Pusher from 'pusher';

const pusher = new Pusher({
  appId: process.env.PUSHER_APP_ID!,
  key: process.env.PUSHER_KEY!,
  secret: process.env.PUSHER_SECRET!,
  cluster: process.env.PUSHER_CLUSTER!,
  useTLS: true
});

export default async function GET(req: Request) {
    try {
      await connectDB();
      const ads = await Advertisement.find({}); 

      console.log('ads in route pusher', process.env.PUSHER_APP_ID)


      let currentAdIndex = 0;
      setInterval(async () => {
        
        const ad = ads[currentAdIndex];
        console.log(`Sending ad: ${currentAdIndex}`, ad);
        await pusher.trigger('ad-channel', 'ad-update', {
          ad
        });
        currentAdIndex = (currentAdIndex + 1) % ads.length;
      }, 20000);

      NextResponse.json({ message: 'Ad rotation started' });
    } catch (error) {
      console.error('Error rotating ads:', error);
    }
  
}