Code of Sword Component:
import { useSession } from "next-auth/react";
import fetch from "isomorphic-unfetch";
const Sword = () => {
const getUser = async () => {
const { data: session } = await useSession();
const res = await fetch(
`http://localhost:3000/api/${(session?.user as any).id}`
);
const data = await res.json();
return { user: data };
};
const user: any = getUser().then((res: any) => {
console.log(res.user.name);
});
return (
<div>
<h1>Sword</h1>
<p>Name: {user.name}</p>
</div>
);
};
export default Sword;
The console log on the constant user
displays the actual name, but when trying to use it down it doesn't display anything. And when using user.user.name
I get an error. How may I fix this issue?
Also when trying to use
console.log(user.name)
below the user constant, it outputs undefined
.
CodePudding user response:
The updated component:
export const Sword = () => {
const dispatch = useDispatch()
const user = useSelector(state => state.user)
useEffect(() => {
dispatch(getUser)
}, [])
return <div>
<h1>{{ user.name }}</h1>
</div>
}
getUser should be a thunk action
CodePudding user response:
New code to fix the issue:
import { useSession } from "next-auth/react";
import fetch from "isomorphic-unfetch";
import { useEffect, useState } from "react";
const Sword = () => {
const [name, setName] = useState("");
const { data: session } = useSession();
useEffect(() => {
const getUser = async () => {
const res = await fetch(
`http://localhost:3000/api/${(session?.user as any).id}`
);
const data = await res.json();
setName(data.name);
return { user: data };
};
getUser();
}, []);
return (
<div>
<h1>Sword</h1>
<p>{name}</p>
</div>
);
};
export default Sword;
Basically I've wrapped my function in a useEffect
and used useState
to set and get the name of the user, doing so seems to have fixed the issue.
Thanks to @Alopwer for letting me know what to do.