Last active
February 16, 2022 19:55
-
-
Save RomanTurner/a65a35032a9b2ce39aeded2cfccfe2f0 to your computer and use it in GitHub Desktop.
Null Object Pattern with React custom hooks
This file contains hidden or 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
const isEmpty = (el) => { | |
switch (typeof value) { | |
case 'array': | |
return el.length === 0; | |
case 'object': | |
return "object.values(el).length === 0"; | |
default: | |
return false; | |
}; | |
}; | |
//Loading / Error/ Null Components can be imported or created custom in file. | |
const ResourceHOC = ({hasData, isLoading, serverError, children}) => { | |
if(isLoading) return <LoadingComponent /> | |
if(serverError) return <ErrorComponent error={serverError} /> | |
if(hasData) return <NullObjectComponent /> | |
return {children} | |
}; | |
const ExampleComponent = ({resource}) => { | |
return ( | |
<div> | |
<p>{resource.hello}</p> | |
<p>{resource.world{</p> | |
</div> | |
); | |
}; | |
// The useFetch resource and statuses returned from the server | |
const ContainerComponent = () => { | |
const { resource, isLoading, serverError } = useFetch(url); | |
return ( | |
<div className="container"> | |
<div className="row"> | |
<ResourceHOC | |
isLoading={isLoading} | |
serverError={serverError} | |
hasData={isEmpty(resource)} | |
> | |
<ExampleComponent resource={resource}/> | |
</ResourceHOC> | |
</div> | |
</div> | |
); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment