'Typescript react setState on context return nothing
I am using the context api to set the current logged in user.
UserContext.ts
const UserContext = createContext<IUser>({} as IUser);
export default UserContext;
The Layout component in which I set the user:
const Layout: React.FunctionComponent<Props> = ({ children }) => {
const router = useRouter();
const [user, setUser] = useState<IUser>({} as IUser);
const getUser = async () => {
const { data } = await axios.get('me');
setUser(data);
}
useEffect(() => {
getUser();
}, []);
return (
<main>
<UserContext.Provider value={user}>
{children}
</UserContext.Provider>
</main>
)
So I fetch the user data from my api, I get the correct data. Then I put the user as a value to my UserContext.Provider.
In another component I try to access the user data like this:
const Movies: NextPage<MovieProps> = props => {
const userContext = useContext(UserContext);
console.log("------------");
console.log(userContext);
console.log("------------");
}
The console just returns an empty object.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
