React – Django : TypeError: Cannot read property ‘token’ of undefined

Tags: , ,



I am trying to login using react and django rest. I have rest-auth for the login backend and users are coming from a LDAP.

The login on django works. Also the response from my backend works too when calling from react.

I tried to save my token in a cookie using react-cookie.

But when I do, I have the error : TypeError: Cannot read property ‘token’ of undefined

I split my code. I have a file api_auth_service.js

export class APILogin {
    static loginUser(body){
        return fetch('http://127.0.0.1:8000/rest-auth/login/', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(body)
        }).then( resp => resp.json())
    }
}

and my login view in react :

export default function Login() {

  const [ username, setUsername] = useState('');
  const [ password, setPassword] = useState('');

  const [token, setToken] = useCookies(['gra-token']);


  useEffect(() => {
    console.log(token);

  }, [token])

  const loginClicked = () => {
    APILogin.loginUser({username, password})
    .then( resp => console.log(resp))
    .then(resp => setToken('gra-token', resp.token))
    .catch( error => console.log(error))
  }

  return ( .............

And what is saved into my cookie is not the token obviously as you can see

enter image description here

Answer

const loginClicked = () => {
 APILogin.loginUser({username, password})
 .then( resp => resp)
 .then(resp => setToken('gra-token', resp.token))
 .catch( error => console.log(error))
}

You need to return the resp from the first then statement



Source: stackoverflow