0

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

1
  • 1
    I think this is because in your first then, you don't return anything, just doing console.log. I would move the setToken to the same then clause you have the console, or return something from the first then clause Commented Oct 24, 2020 at 11:25

1 Answer 1

1
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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.