0

i have been trying to create a hook that fetches data and takes advantage of react suspense. Using the example in the page (and this article) I have created a function(i want to convert it to hook) that fetches data.

Example

Here on codesandbox

Problem

Currently I can't pass data through the function as it gets executed when it is called.I want to pass data in useWrap(**HERE**) and use it in fetchData()

Expected behaviour / Target

  1. I want to pass data to useWrap() and put it in fetchData()
  2. I want the useWrap to be a Hook in order to take advantage of basic hooks
  3. I want to take advantage of React Suspense

Does someone know how to accomplish these needs and tell me what am i doing wrong?

Thank you!

skyboyer
  • 22,209
  • 7
  • 57
  • 64

1 Answers1

0

This should do the trick for you and is more react-like than what you had originally.

Api.js

import React, { useEffect, useState } from "react";

export default function useWrap(id) {
  const [apiData, setApiData] = useState({});
  const [error, setError] = useState(null);

  useEffect(() => {
    (async () => {
      await fetch(`https://jsonplaceholder.typicode.com/users/${id}`)
        .then(async (res) => await res.json())
        .then((result) => setApiData(result))
        .catch((err) => setError(err));
    })();
  }, [id]);

  return error ? error : apiData;
}

ProfileDetail.js

import React from "react";
import useWrap from "./Api";

export default function ProfileDetails() {
  const user = useWrap(1);

  if (user === null) {
    return;
  }

  return <div>{user.id}</div>;
}
Harben
  • 1,802
  • 1
  • 11
  • 16
  • Hi! thank you for the answer but it doesn't work the way i wat as it doesn't trigger the Suspense I added some logs to your example to let you see that the suspense is not triggered [here in sandbox](https://codesandbox.io/s/peaceful-bhaskara-wycw3?file=/src/App.js) Suspense doesn't trigger as in the `Api.js` is not thrown a promise as stated in the example of React Documentation – Michelangelo De Francesco Aug 15 '20 at 17:56