Using useSWR to retrieve data from an endpoint, but I am getting this error (I want to only retrieve the data 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);
)
The fetchUsers function is being called here onclick:
<Box>
<Button
onClick= setShouldFetch(true)
>
View User
</Button>
</Box>
the block of code below should render the retrieved API response. If setShouldFetch is true, then the API response is rendered, if not, something else is rendered. Here's my current implementation, but it's returning an error
cannot read properties of undefined (reading 'name)
<Typography
>
shouldFetch? data.name : Students Portal
</Typography>
This is what the expected response looks like:
{
"name": [
{
"id": "8",
"age": "10"
},
{
"id": "4",
"age": "11",
}
],
"id": "71"
}