简体   繁体   中英

Pass props to axios hook that implements react suspense

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!

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>;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM