Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"useSWR is called in function that is niether a React function component nor a custom React Hook function" Error

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"
    }
like image 319
Tini Avatar asked Feb 07 '26 06:02

Tini


1 Answers

You want conditional data fetching

In your example I think it could be something like this:

const [shouldFetch,setShouldFetch] = useState(false)
const fetcher = (url) => axios.get(url).then((res) => res.data);
const { data, error } = useSWR(shouldFetch ? 'http://...' : null,fetcher)

return (
       <Box>
        <Button
          onClick={() => setShouldFetch(true)}
        >
          View User
        </Button>
      </Box>
)

To discuss this a little bit, with declarative data fetching the fetch is called immediately and automatically when the component is rendered unless you make it conditional. In the case of useSWR it won't fetch automatically if your key (first parameter to useSWR) is null or is a function that returns null or is a function that throws an error.

like image 158
Adam Avatar answered Feb 09 '26 07:02

Adam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!