{"size": 1266, "ext": "js", "max_stars_repo_path": "client/src/context/AuthContext.js", "max_stars_repo_name": "RickBr0wn/jwt-auth", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "client/src/context/AuthContext.js", "max_issues_repo_name": "RickBr0wn/jwt-auth", "max_issues_repo_issues_event_min_datetime": "2021-03-10T16:43:51.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-27T04:00:18.000Z", "max_forks_repo_path": "client/src/context/AuthContext.js", "max_forks_repo_name": "RickBr0wn/jwt-auth", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": null, "max_issues_count": 8, "max_forks_count": null, "avg_line_length": 25.32, "max_line_length": 77, "alphanum_fraction": 0.6769352291}
import React, { createContext, useContext, useState, useEffect } from 'react'
import PropTypes from 'prop-types'
import AuthService from '../services/AuthService'

const AuthContext = createContext()

const AuthProvider = ({ children }) => {
  // TODO: convert to useReducer
  const [user, setUser] = useState(null)
  const [isAuthenticated, setIsAuthenticated] = useState(false)
  const [isLoaded, setIsLoaded] = useState(false)

  useEffect(() => {
    if (!isLoaded) {
      AuthService.isAuthenticated().then(data => {
        setUser(data.user)
        setIsAuthenticated(data.isAuthenticated)
        setIsLoaded(true)
      })
    }
    return () => {}
  }, [isLoaded])

  if (!isLoaded) {
    return <h1>Loading data..</h1>
  }

  // TODO: set API so the user does not need to use the useContext hook
  return (
    <AuthContext.Provider
      value={{ user, setUser, isAuthenticated, setIsAuthenticated }}>
      {children}
    </AuthContext.Provider>
  )
}

AuthProvider.propTypes = {
  children: PropTypes.object,
}

function useAuthContext() {
  const context = useContext(AuthContext)
  if (context === undefined) {
    throw new Error('useAuthContext must be used within a AuthProvider')
  }
  return context
}

export { AuthProvider, useAuthContext }
