Next.js Discord

Discord Forum

Best way to fetch & refetch data on client side components (app dir)

Western thatching ant posted this in #help-forum
Open in Discord
Western thatching antOP
Hey, here is the situation:

- App directory
- Client side component
- Trying to fetch data from the client side component, and periodically refetch the data (every 5 seconds, for example)
- I'm used to tRPC, but it doesn't currently work with the app dir unless you wrap everything in a client side provider, but that kinda defeats the purpose of RSCs.
- How to factor in type safety on both client (component) and server side (endpoint handler) for client side fetching?

Interested in hearing any insights on how to fetch & refetch data periodically on a client side component while keeping type safety with the App directory.

Of course, there is the idea of just calling router.refresh() every 5 seconds, but that would make it impossible to include animations on the UI as the data changes in real-time as it would be a server side refetch (unless I'm wrong here?).


1 Reply

Western thatching antOP
Here's an example of what I'm talking about:

"use client";
// ....
const StatusWidget = ({order}: StatusWidgetProps) => {

    const [items, setItems] = useState<Video[]>([]);
    const [deliveredItemsCount, setDeliveredItemsCount] = useState<number>(0);

    useEffect(() => {
        const timer = setInterval(async () => {
            // Any better way to do this, in a typesafe way
            const response = await fetch(`/api/orders/${}/items`)
            const data = await response.json();
        }, 5000)

        return () => {
    }, [])

    useEffect(() => {
        const newDeliveredItemsCount = => video.status === Status.DELIVERED).length;
    }, [items])

  return (
        Total delivered items: {deliveredItemsCount}

On the server-side, it would then handle authorization, mutate data, query data from database, etc. --> then return the response

The issue here is that there is no type safety on either sides of this request - everything would have to be checked. And with tRPC broken at the moment, I was wondering if any of you all have had the chance to think of ways to work around this?