I trying to use useSWR at the click of the button. I would that the at the click of the button the API call with useSWR will start, but I get the error. The error is this :
Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.
This is my code :
const onStartPro =() => {
const token = session?.user?.access_token
const url = process.env.BASE_URL + GET_PRO
const {
data: items,
error,
isLoading,
} = useSWR(process.env.BASE_URL + 'pro user', getAuthenticatedClientSide(token,GET_PRO))
}
And this is my get function:
export const getAuthenticatedClientSide = async (token, endpoint) => {
const url = process.env.BASE_URL + endpoint
try {
const res = await wretch(url).auth(`Bearer ${token}`).get().json()
return res
} catch (e) {
const error = new Error(e)
error.info = e.message
error.status = e.status
throw error
}
}
Where am I wrong ? Help me please :(
useSwr is a hook fun, it will be same like useEffect. so you can not use inside of event function. you should try axios or fetch, just like a normal function ccall inside of your event fun.
use fetcher function
export const fetcher = async (path: string) => {
const res = await fetch(`${API_URL}${path}`, {
headers: {
Authorization: TOKEN || '',
Accept: 'application/json, text/plain, */*',
'User-Agent': '*'
}
});
const res = await fetcher(`/users`);