Reputation: 1
I need to pass token from session (NextAuth) to my api request. But useSession is a hook and I can't use it on server components, but when I add await to a fetching function it becomes a server component. Here is an example code:
"use client";
import axios from "axios";
import { useSession } from "next-auth/react";
const fetchData = (token) => {
const config = {
'Authorization': `Token ${token}`
}
const response = axios.get('http://myAPI.com/data', config )
return response.data;
}
export default Home = async () => {
const {data: session} = useSession();
const data = await fetchData(session?.token);
return (
<main>
<h1>{data.title}</h1>
</main>
)
}
So how can I properly solve this problem, if I need hooks while fetching ?
Here is my dependencies:
"dependencies": {
"@reduxjs/toolkit": "^1.9.5",
"axios": "^1.4.0",
"eslint": "8.47.0",
"eslint-config-next": "13.4.19",
"formik": "^2.4.3",
"next": "13.4.19",
"next-auth": "^4.23.1",
"react": "18.2.0",
"react-dom": "18.2.0",
"react-icons": "^4.10.1",
"react-redux": "^8.1.2",
"yup": "^1.2.0"
}
Upvotes: 0
Views: 470
Reputation: 4146
You need to move the await
inside a useEffect
hook:
export default Home = async () => {
const {data: session} = useSession();
const [data, setData] = useState();
useEffect(() => {
fetchData(session?.token).then(setData);
}, [])
return (
<main>
<h1>{data?.title}</h1>
</main>
)
}
The await
will now not prevent the component from being rendered (that wasn't the case earlier and hence your issue). And once the data is fetched, the component shall be re-rendered with the updated title.
Upvotes: 0