Skip to content

Instantly share code, notes, and snippets.

@Phoenix-GH
Created July 21, 2021 03:12
Show Gist options
  • Save Phoenix-GH/9dd86aeb1cb0661568e30389b1dc85ab to your computer and use it in GitHub Desktop.
Save Phoenix-GH/9dd86aeb1cb0661568e30389b1dc85ab to your computer and use it in GitHub Desktop.
Gist for the interview for Contra
/**
* In this short assessment, the following code tries to implement the React Suspense API,
* but does so incorrectly. There are 3 core issues with how these components utilize Suspense and concurrent mode -- can you find them?
*
* In your submission, be sure to:
* 1) Clearly identify what the 3 core issues are, and how they violate the principles of React Suspense;
* 2) Write and submit the code to fix the core issues you have identified in a gist of your own
*
* If you aren't familiar with Suspense, the docs are a good starting place:
*
* https://reactjs.org/docs/concurrent-mode-intro.html
*
* We rate each answer by comparing the submitted answer to how we would write the same code in production at Contra.
* You are guaranteed an interview if your code ticks all the boxes. Good luck!
*/
import { Suspense, useState, useEffect } from 'react';
// we need to provide fallback to suspence
// we need to provide error boundary for network calls
// we need to begin fetching data before rendering, so I guess we should begin fetching in UserProfileList where we know all parameters needed
class ErrorBoundary extends React.Component {
state = { hasError: false, error: null };
static getDerivedStateFromError(error) {
return {
hasError: true,
error
};
}
render() {
if (this.state.hasError) {
return this.props.fallback;
}
return this.props.children;
}
}
const SuspensefulUserProfile = (resource) => {
const data = resource.read();
return (
<ErrorBoundary fallback={<h2>Could not fetch user data.</h2>}>
<Suspense fallback={<h1>Loading user data...</h1>}>
<UserProfile data={data} />
</Suspense>
<ErrorBoundary fallback={<h2>Could not fetch user data.</h2>}>
);
};
const UserProfile = ({ data }) => {
return (
<>
<h1>{data.name}</h1>
<h2>{data.email}</h2>
</>
);
};
const resourses =
{
"1": fetchUserData(1),
"2": fetchUserData(2),
"3": fetchUserData(3)
};
const UserProfileList = (resourses) => (
<>
<SuspensefulUserProfile userId={resources["1"]} />
<SuspensefulUserProfile userId={resources["2"]} />
<SuspensefulUserProfile userId={resources["3"]} />
</>
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment