Home > Enterprise >  useContext causing blank screen
useContext causing blank screen

Time:03-13

The app uses useContext for state management and axios for a get request to an API to receive data. Originally I was not using useContext but later realized state will be needed in multiple components later down the road and props would be messy. The app was working perfectly prior to using useContext now I am receiving a blank screen and no error messages.

ThemeContext.js

import {useState, useEffect, createContext} from 'react'
import axios from 'axios'
const ThemeContext = createContext()

const ThemeContextProvider = props => {

  const [students, setStudents] = useState([])
  const [loading, setLoading] = useState(false)


  useEffect(()=>{
    getStudents()
  },[])

  const getStudents = async () => {
    try {
          const res = await axios.get('https://api.hatchways.io/assessment/students')
          setStudents(res.data.students)
          setLoading(true)
    }
    catch (err) {
      console.log(err.message)
    }
  }

  return (
      <ThemeContextProvider.Provider value={{students, loading}}>
          {props.children}
      </ThemeContextProvider.Provider>
  )

}

export {ThemeContextProvider, ThemeContext}

Students.js

import {useContext} from 'react'
import {ThemeContext} from './themeContext'


const Students = props => {

  const {students, loading} = useContext(ThemeContext)  
 
  return (
    <div>
        {loading &&
         students.map((student) =>(
                <div className="student-profile-container">

                      <div className="student-profile-image">
                        <img key={student.id} src={student.pic} alt="student profile avatar"/>
                      </div>
                      <div className="student-profile-info">
                          <h1 className="student student-name">{student.firstName} {student.lastName}</h1> 
                          <p className="student student-info">Email: {student.email}</p>
                          <p lassName="student student-info">Company: {student.company}</p>
                          <p className="student student-info">Skill: {student.skill}</p>
                          <p className="student student-info">Average: {student.average}%</p>

                       
                      </div>
                    
                </div>
               
            ))
        }
    </div>
  );
}

export default Students;

CodePudding user response:

It appears you are mixing up ThemeContext and ThemeContextProvider. Changing the return value of ThemeContextProvider should fix your issue.

<ThemeContext.Provider value={{students, loading}}>
   {props.children}
</ThemeContext.Provider>
  • Related