Skip to main content

HOC with hooks - testing hooks

https://github.com/testing-library/react-hooks-testing-library

export const Foo = ({ bar }) => {
  const { result, loading, error } = useRequest(bar);
  if (error) {
    return <ErrorComponent />;
  } else if (loading) {
    return <LoadingComponent />;
  }
  return <ResultComponent result={result} />;
};

This looks reasonably good at a glance, but what about when we have to repeat this pattern for a dozen different requests? You would copy and paste this conditional block to each of those different implementations and in each of them, it would need to be tested on its own.
An HoC implementation could resemble something like this:
const Foo = ({ result }) => <ResultComponent result={result} />;const withRequest = BaseComponent => ({ bar, ...props }) => { const { result, loading, error } = useRequest(bar); return ( <BaseComponent {...props} result={result} loading={loading} error={error} /> ); };const withError = branch(({ error }) => error, ErrorComponent);const withLoading = branch(({ loading }) => loading, LoadingComponent);export default compose( withRequest, withLoading, withError )(Foo);

Prop Mutation

const Result = ({ bar }) => <ResultComponent result={bar} />;const withBar = BaseComponent => ({ foo, ...props }) => (
  <BaseComponent {...props} bar={transform(foo)} />
);export default withBar(Result);
const ResultComponent = (props) => {
const { hello } = props
return (
<div>
<h1>{hello}</h1>
</div>
)
}
ResultComponent.propTypes = {
hello: PropTypes.string.isRequired,
};
const withHello = BaseComponent => (props) => {
const { name } = props
const str = `Hi ${name}`
return <BaseComponent hello={str} />
}
const Hello = withHello(
ResultComponent
);
<Hello name='Joe' />

Comments

Popular posts from this blog

About GraphQL - Downside

Web caching complexity

File uploading. Since GraphQL doesn’t understand files, a file uploading feature is not included in its specification. You won’t have to deal with this limitation in case of REST, as there you can POST or PUT whatever content you want to.
To allow file uploads in your GraphQL web app, there are several options: using Base64 encoding. But it will make the request larger and expensive to encode/decode.making a separate API endpoint just for this purpose.using a library like Apollo for implementing the GraphQL multipart request specification.uploadFileToS3:combineResolvers( // isAuthenticated, async (parent, args, { models }) => { const { file } = awaitargs const { createReadStream, filename, mimetype, encoding } = awaitfile conststream = createReadStream() constresult = awaituploadFileToS3(filename, stream) returnresult } ),