Im building an AuthContext in react to handle login, i connect it to a django backend where i validate the user and then i get an authorization token
import React, { createContext, useState, useEffect} from 'react';
import axios from 'axios';
export const AuthContext = createContext();
export const AuthProvider = ({ children }) => {
const [token, setToken] = useState(null);
const login = async (username, password) => {
try {
const response = await axios.post('http://127.0.0.1:8000/token/', {
username,
password
});
console.log('Response data:', response.data);
const { token: responseToken } = response.data;
setToken(responseToken);
console.log('Token loaded:', responseToken);
} catch (error) {
console.error('Error en el inicio de sesión:', error);
}
};
useEffect(() => {
console.log('Token actual value:', token);
}, [token]);
return (
<AuthContext.Provider value={{ token, login }}>
{children}
</AuthContext.Provider>
);
};
From my backend i get the expected answer, an status 200 with the token that i expect, but after assign the response.data to responseToken, in the next log it shows that is undefined. Here is the output in the navigator console:
Tried to change the variable names to check if there is a conflict between those declared there, but the problem persists.
Your console log shows that response data has two properties refresh
& access
. But you are trying to get a property called token
, which does not exist (or at least it's not visible in your screenshot).
const { access: responseToken } = response.data;
This should help. (if access
is the one you actually need)