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
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
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.