AtharvaA
tRPC3y ago
1 reply
Atharva

How to make LoaderAndError component which is type safe?

I i have a query like this const { data, isLoading, isError } = trpc.settings.get.useQuery();

Now I have a LoaderAndErrorComponent like below
import React from 'react'
import { Loader } from './Loader'
import { PiSmileySadLight } from 'react-icons/pi';

interface LoaderAndErrorProps {
    loading: boolean,
    error: boolean
    children?: React.ReactNode
}

export const LoaderAndError: React.FC<LoaderAndErrorProps> = ({ error, loading, children }) => {


    if (loading) {
        return <div className='flex items-center justify-center flex-1'><Loader /></div>
    }

    if (error) {
        return <div className='flex items-center justify-center flex-1 gap-2'><PiSmileySadLight /> Some Error Getting Data!</div>
    }

    return (
        <>{children}</>
    )
}


Now when i am wrapping this LoaderAndError component around a Component and trying to access the data in Component the type is WhateverDataType | undefined
basically TS doesn't know that the Component won't be reached with undefined data
What is a good way to do this ?
Was this page helpful?