I receive the data for the user object by an api call. Inside the getSelectedUser function, the console.log returns the filled user object. But in the console.log in the useEffect returns an empty object. What am I doing wrong?
Foo.tsx
const [user, setUser] = useState<IUser>(initialUser);
useEffect(() => {
getSelectedUser();
console.log(user);
}, []);
async function getSelectedUser() {
await getUserById(userId).then((data) => {
setUser(data);
console.log(data);
});
}
Service.tsx
export const getUserById = async (userId: string | number) => {
const user = ...;
const token = ...;
try {
const response = await fetch(`${apiurl}/${userId}`, {
method: 'GET',
...
}).then((res) => res.json());
return response;
} catch (error) {
console.log(error);
}
};