I am working through The Net Ninja's
index.js
import React from 'react';
import ReactDOM from 'react-dom/client';
import { AuthContextProvider } from './context/AuthContext';
import './index.css';
import App from './App';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<AuthContextProvider>
<App />
</AuthContextProvider>
</React.StrictMode>
)
useSignup.js
import { useState } from "react";
import { useAuthContext } from './useAuthContext'
export const useSignup = () => {
const [error, setError] = useState(null)
const [isLoading, setIsLoading] = useState(null)
const { dispatch } = useAuthContext()
const signup = async (email, password) => {
setIsLoading(true)
setError(null)
const response = await fetch('http://localhost:4000/api/user/signup', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({email, password})
})
const json = await response.json()
if (!response.ok) {
setIsLoading(false)
setError(json.error)
}
if (response.ok) {
// save the user to local storage
localStorage.setItem('user', JSON.stringify(json))
// Update the auth context
dispatch({type: 'LOGIN', payload: json})
setIsLoading(false)
}
}
return { signup, isLoading, error }
}
AuthContext.js
import { createContext, useReducer } from 'react'
export const AuthContext = createContext()
export const authReducer = (state, action) => {
switch(action.type) {
case 'LOGIN':
return {
user: action.payload
}
case 'LOGOUT':
return {
user: null
}
default:
return state
}
}
export const AuthContextProvider = ({ children }) => {
const [state, dispatch] = useReducer({ authReducer }, { user: null })
return (
<AuthContext.Provider value={{...state, dispatch}}>
{ children }
</AuthContext.Provider>
)
}
useAuthContext.js
import { AuthContext } from "../context/AuthContext";
import { useContext } from "react";
export const useAuthContext = () => {
const context = useContext(AuthContext)
if (!context) {
throw Error('useAuthContext must be used inside an AuthContextProvider')
}
return context
}
CodePudding user response:
Read the error message: remove the { } around { authReducer }