useContext returns null value in some components

Viewed 39

I have a react component index.js that fetches the user information from a Laravel server through a fetch call. The information is provided to the context UserContext, which is declared in a separate file and imported, near the top-level of the app as follows.

UserContext.jsx

import { createContext } from "react";
const UserContext = createContext(null);
export default UserContext;
const [user, setUser] = useState(null);
useEffect(() => {
 // Get logged in user
 fetch('/user', {
     method: 'GET',
     headers: {
         'Content-Type': 'application/json'
     },
     credentials: 'include'
     }).then(res => res.json()).then(data => {
         setUser(data);
     }).catch(err => {
         setUser(null)
     });
}
return (
       <UserContext.Provider value={user}>
            <Header/>
            <main>
                <BrowserRouter>
                    <Routes>
                        <Route path="/" element={<Home categories={categories} />} />
                        <Route path="/login" element={<Login />} />
                        <Route path="/register" element={<Register />} />
                        <Route path="/profile/:id" element={<Profile />} />
                        <Route path="/profile/:id/edit" element={<EditProfile />} />
                        <Route path="/profile/:id/registrations" element={<MyRegistrations />} />
                        <Route path="/posts" element={<Posts />}></Route>
                        <Route path="/posts/:id" element={<Post categories={categories} />}></Route>
                        <Route path="/category/:id" element={<Posts />} />
                        <Route path="/403" element={<Error error={403} />} />
                        <Route path="/404" element={<Error error={404} />} />
                        <Route path="/500" element={<Error error={500} />} />
                        <Route path="*" element={<Error error={404} />} />
                    </Routes>
                </BrowserRouter>
            </main>
            <Footer/>
        </UserContext.Provider>
    );

When I try to access user in <Header>, it works as expected. However, in the routes nested in the react-router-dom <Routes>, it returns null.

Header.jsx, Post.jsx declaration to access user

    const user = useContext(UserContext);

I suspected that this could be caused because of the context provided by react-router-dom or the nesting, so I tried to pull <Post/> to the top level and disable react-router-dom but it seems to be the same issue.

Post.jsx

import { useState, useEffect, useContext } from 'react';
import React from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import * as DOMPurify from 'dompurify';
import { Container } from 'react-bootstrap';
import UserContext from '../context/userContext';

export default function Post({ categories }) {
    const user = React.useContext(UserContext);

    let navigate = useNavigate();

    let params = useParams();
    const [id, setId] = useState(params.id);
    const [post, setPost] = useState(null);

    const [registered, setRegistered] = useState(false);
    const inCourse = (id, courses) => {
        console.log(id, courses);
        return courses.filter(course => course.id == id).length > 0;
    }

    const inEvent = (id, events) => {
        return events.filter(event => event.id == id).length > 0;
    }


    useEffect(() => {
        {/* fetch post from api, works correctly */}
    }, [id]);

    useEffect(() => {

    }, [user, id]);

    return (
        {/* unnecessary jsx */}
    );
}
0 Answers
Related