Skip to content

Instantly share code, notes, and snippets.

@RomanTurner
Last active February 16, 2022 19:55
Show Gist options
  • Save RomanTurner/a65a35032a9b2ce39aeded2cfccfe2f0 to your computer and use it in GitHub Desktop.
Save RomanTurner/a65a35032a9b2ce39aeded2cfccfe2f0 to your computer and use it in GitHub Desktop.
Null Object Pattern with React custom hooks
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