Next.js Discord

Discord Forum

Unable to get Advertisement on real time (socket.io)

Unanswered
Northeast Congo Lion posted this in #help-forum
Open in Discord
Northeast Congo LionOP
I am using socket.io for real time ads showing on client side but its not working as expected, showing blank. If I use get request with useEffect, it will render but its not real time and all user can't see same ads

route file
import Advertisement from "@/lib/database/models/advertisement.model";
import { connectDB } from "@/lib/database/mongoose";
import { NextResponse } from "next/server";
import { Server } from "socket.io";

let ads:any = [];
let currentAdIndex = 0;
const io = new Server();

export async function GET(req: Request) {
    const url = new URL(req.url);
    const limit = parseInt(url.searchParams.get("limit")!) || 100;

    try {
        await connectDB();
        ads = await Advertisement.find().limit(limit);

        setInterval(() => {
            if (ads.length > 0) {
                currentAdIndex = (currentAdIndex + 1) % ads.length;
                io.emit('adUpdate', ads[currentAdIndex]); // Broadcast ad updates to all connected clients
            }
        }, 20000); // Rotate ad every 20 seconds

        return NextResponse.json({
            message: "Ads fetched successfully",
        });
    } catch (error) {
        console.error("Error in Fetch Ads Get:", error);
        return NextResponse.json({ message: 'Failed to fetch ads', status: 500 });
    }
}

1 Reply

Northeast Congo LionOP
Adbox component
import { useEffect, useState } from 'react';
import io from 'socket.io-client';

const socket = io();

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

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

    useEffect(() => {
        socket.on('adUpdate', (updatedAd) => {
            console.log(updatedAd, updatedAd)
            setCurrentAd(updatedAd);
        });

        return () => {
            socket.disconnect();
        };
    }, []);

    return (
        <div>
            {currentAd && (
                <div>
                    <img src={currentAd.image} alt="Advertisement" />
                    <a href={currentAd.link} target="_blank" rel="noopener noreferrer">Visit Ad</a>
                </div>
            )}
        </div>
    );
};

export default AdBox;