0

I was given a project to find out why the below lines of code isn't working. The following code implement the React Suspense API, but does so incorrectly. There are 3 core issues with how these components utilize Suspense and concurrent mode which is something I'm not Familiar with and even after reading the documentation I still can't fix it

import { Suspense, useState, useEffect } from 'react';

const SuspensefulUserProfile = ({ userId }) => {
  const [data, setData] = useState({});
  useEffect(() => {
    fetchUserProfile(userId).then((profile) => setData(profile));
  }, [userId, setData])
  return (
    <Suspense>
      <UserProfile data={data} />
    </Suspense>
  );
};
const UserProfile = ({ data }) => {
  return (
    <>
      <h1>{data.name}</h1>
      <h2>{data.email}</h2>
    </>
  );
};
const UserProfileList = () => (
  <>
    <SuspensefulUserProfile userId={1} />
    <SuspensefulUserProfile userId={2} />
    <SuspensefulUserProfile userId={3} />
  </>
);
The Newbie
  • 11
  • 8

3 Answers3

2

For Suspense to have any value, you want to load a component asynchronously. That usually translate on doing dynamic imports.

export default const UserProfile = ({ data }) => {
  return (
    <>
      <h1>{data.name}</h1>
      <h2>{data.email}</h2>
    </>
  );
};

You then import UserProfile only when's needed with React's lazy:

const UserProfile = React.lazy(() => import('./UserProfile'))

And use it:

<Suspense fallback={'Loading...'}>
  <UserProfile data={data} />
</Suspense>
Federkun
  • 36,084
  • 8
  • 78
  • 90
0

You will have to pass fallback. Without fallback it wont work.

<Suspense fallback={<div>Loading</div>}>
or
<Suspense fallback={<></>}>
Ashiq Dey
  • 309
  • 5
  • 18
0

What worked for me is lazy loading, from Federkun's example:

const UserProfile = React.lazy(() => import('./UserProfile'))

One note is that it only works if the eslint parser is set to:

"parser": "babel-eslint"

Philip Sopher
  • 627
  • 2
  • 8
  • 19