使用useSWR从端点检索数据,但我收到了这个错误(我只想在onClick上检索数据)
"useSWR is called in function `fetchUsers` that is niether a React function component nor a custom React Hook function" Error
const [shouldFetch,setShouldFetch] = useState(false)
const fetcher = (url) => axios.get(url).then((res) => res.data);
const { data, error } = useSWR(shouldFetch ? "http://localhost:5000/users": null, fetcher);
)
在此处onClick调用fetchUser函数:
<Box>
<Button
onClick= setShouldFetch(true)
>
View User
</Button>
</Box>
下面的代码块应该呈现检索到的API响应.如果setShouldFetch为真,则呈现API响应,否则呈现其他内容.下面是我当前的实现,但它返回了一个错误
cannot read properties of undefined (reading 'name)
个
<Typography
>
shouldFetch? data.name : Students Portal
</Typography>
以下是预期的回应:
{
"name": [
{
"id": "8",
"age": "10"
},
{
"id": "4",
"age": "11",
}
],
"id": "71"
}