Last active
June 22, 2023 16:27
-
-
Save DarlonHenrique/0519b30c28d187802eaccdc207c98194 to your computer and use it in GitHub Desktop.
Query Results conditionally renders Apollo useQuery hooks states: loading, error or its children when data is ready.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from 'react'; | |
// usage example: | |
/* | |
<QueryResult error={error} loading={loading} data={data}> | |
{data?.tracksForHome?.map((track) => <TrackCard key={track.id} track={track} />))} | |
</QueryResult> | |
*/ | |
/** | |
* Query Results conditionally renders Apollo useQuery hooks states: | |
* loading, error or its children when data is ready | |
*/ | |
const QueryResult = ({ loading, error, data, children }) => { | |
if (error) { | |
// customize your error here | |
return <p>ERROR: {error.message}</p>; | |
} | |
if (loading) { | |
return ( | |
// customize your loading here | |
<div> | |
<span>Loading...</span> | |
</div> | |
); | |
} | |
if (!data) { | |
// customize when you dont have data to show but the query work fine | |
return <p>Nothing to show...</p>; | |
} | |
if (data) { | |
// return the children, wrap this component around you query | |
/* | |
<QueryResult error={error} loading={loading} data={data}> | |
{data?.tracksForHome?.map((track) => <TrackCard key={track.id} track={track} />))} | |
</QueryResult> | |
*/ | |
return children; | |
} | |
}; | |
export default QueryResult; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment