Problem : I have a function which always keeps the context
, the problem is that when passing from that function react
to a component of , react
it is lost and the next page is not able to retrieve the context
, even so for some reason the is saved context
in the login.js
but when I go to the other component and perform a static contexto = userContext
, I end up losing it, also inside the component it is not allowed to use React.useContext()
.
User.js
import React from "react";
export const userContext = React.createContext('false');
export const setUserContext = React.createContext('false');
Login.js
async function loginUser(credenciales, setUserInfo) {
const url = "http://localhost:8000/api/Usuarios/?search=" + credenciales.usuario;
const response = await axios.get(url);
const data = await response.data;
if(data.length > 0){
if(data[0].password === credenciales.password){
setUserInfo(data[0].nombre);
}
else{
alert('Comprueba los datos introducidos');
}
}
else{
alert('Comprueba los datos introducidos');
}
}
const userInfo = React.useContext(userContext);
const setUserInfo = React.useContext(setUserContext);
const [usuario, setUsuario] = React.useState({});
const [password, setPassword] = React.useState({});
console.log(userInfo);
const handleLogin = async (e) => {
e.preventDefault();
await loginUser({
usuario,
password,
}, setUserInfo);
};
CompraVenta.js
When performing one of the functions here console.log(context)
, it remains empty.
import React from "react";
import axios from "axios";
import {userContext} from "./user";
export default class Compraventa extends React.Component {
static context = userContext;
}
I think that the best way to occupy the context is like this:
You would create this in a folder called context and inside it a file called user-context.js (the truth is that you only need to make the file with the name you like but as I indicate it is more organized)
and in your _app.js or in your main file do the following: