[英]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 .我一直在尝试创建一个获取数据并利用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()
目前我无法通过 function 传递数据,因为它在被调用时被执行。我想在useWrap(**HERE**)
中传递数据并在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 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 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>;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.