开发者

"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",
            }
        ]开发者_JAVA技巧,
        "id": "71"
    }


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜