Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am getting following error when I testing hooks with async function;

Invariant Violation Objects are not valid as a React child (found: [object Promise]).

async function Test () {
  const data = await fetch('https://jsonplaceholder.typicode.com/posts/42');
  const json = await data.json();  
  const id = json.id;
  return id;
}

...

function App() {
  return (
    <div className="App">
      <h1>React Hooks Example</h1>

      <Suspense fallback={<LoadingMessage />}>
        <Test />
      </Suspense>

    </div>
  );
}

https://codesandbox.io/s/4w2yzvyro7

How can I fix this error

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
178 views
Welcome To Ask or Share your Answers For Others

1 Answer

<Suspense> is supposed to be used in very specific manner. It suspends the rendering of lazy components and renders other kinds of components as is.

Test is not lazy component but async function, it returns promise object and not React element, hence Test is not a valid React component.

lazy components are aimed at rendering default imports from lazily loaded components. Basically lazy component should return a promise of an object with default property that contains valid React component.

It can be used as:

const Test = lazy(async () => {
  const data = await fetch('https://jsonplaceholder.typicode.com/posts/42');
  const json = await data.json();  
  const id = json.id;

  return { default: (props) => <div>{id}</div> };
});

...

<Suspense fallback={<LoadingMessage />}>
  <Test />
</Suspense>

Notice that due to its primary use case, lazy component can't accept parameters, if Test had props, they would be passed to a component that async function returns.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...