No entiendo por qué sigue ocurriendo el siguiente error, ¡así que realmente me vendría bien un poco de ayuda!
Error:
Login.jsx:10 Uncaught TypeError: Cannot destructure property 'user' of '(0 , react__WEBPACK_IMPORTED_MODULE_1__.useContext)(...)' as it is undefined. at Login (Login.jsx:10:1)Contexto.js:
import { createContext, useEffect, useReducer } from "react"; import Reducer from "./Reducer"; const INITIAL_STATE = { user: null, isFetching: false, error: false, }; export const Context = createContext(INITIAL_STATE); export const ContextProvider = ({ children }) => { const [state, dispatch] = useReducer(Reducer, INITIAL_STATE); return ( <Context.Provider value = {{ user: state.user, isFetching: state.isFetching, error: state.error, dispatch, }} > {children} </Context.Provider> ); };Iniciar sesión.js:
import axios from 'axios'; import { useContext, useRef } from 'react'; import { Link } from 'react-router-dom'; import { Context } from '../../context/Context'; import './login.css'; export default function Login() { const userRef = useRef(); const passwordRef = useRef(); const { user, dispatch, isFetching } = useContext(Context); //error const handleSubmit = async (e) => { e.preventDefault(); dispatch({ type: 'LOGIN_START' }); try { const res = await axios.post(`http://localhost:5000/api/auth/login`, { username: userRef.current.value, password: passwordRef.current.value, }); dispatch({ type: 'LOGIN_SUCCESS', payload: res.data }); } catch (err) { dispatch({ type: 'LOGIN_FAILURE' }); console.log(err); } }; console.log(user); return ( <div className='login'> <span className='loginTitle'>Login</span> <form className='loginForm' onSubmit={handleSubmit}> <label>Username</label> <input type='text' className='loginInput' placeholder='Enter your username...' ref={userRef} /> <label>Password</label> <input type='password' className='loginInput' placeholder='Enter your password...' ref={passwordRef} /> <button className='loginButton' type='submit' disabled={isFetching}> Login </button> </form> <button className='loginRegisterButton'> <Link className='link' to='/register'> Register </Link> </button> </div> ); }¿Envolvió el padre del componente de inicio de sesión con ContextProvider?
import { ContextProvider } from '../../context/Context'; import Login from "..." function App() { return( <> <ContextProvider> <Login> //any other child over here can access the context from this provider </ContextProvider> </> ) } export default App;