1

So I'm attempting to make an authentication system using tokens. This works via sending a get request with a token in it and the API is supposed to give information back. I'm encountering an error which is TypeError: Cannot read property 'Error' of undefined and the error is pointing to this line if (UserData.Error == "Token not valid") {return false}. So I'm guessing this means the response of API is not getting put into UserData. The API works fine and here is the response if the token is right:

{
    "username": "admin",
    "is_staff": true,
    "email": "admin@gmail.com"
}

Here is the response when token is not right

{
    "Error": "Token not valid"
}

Here is my code:

function isAuthenticated() {
    const authtoken = localStorage.getItem('AuthToken')
    if (authtoken == null) {
        return false
    } else {
        let UserData;
        axios.get(`http://localhost:8000/api/token/?token=${authtoken}`).then(function(request) {
            UserData = request.data
        })
        if (UserData.Error == "Token not valid") {return false}
        else {return UserData}
    }
}
SnaccOvenFlour
  • 158
  • 3
  • 14
  • Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – zero298 Apr 15 '21 at 17:26
  • I do not think it does – SnaccOvenFlour Apr 15 '21 at 17:28
  • 1
    It does, that `if (UserData.Error == "Token not valid") {return false}` doesn't wait for the axios call directly above it. It executes immediately which means that `UserData` will ***never*** be defined by the time you reach that if. – zero298 Apr 15 '21 at 17:30
  • Have you implemented the error handling like `catch` on the fetch or the `axios.get`? I think you should put the `catch` after `then` – Dhana D. Apr 15 '21 at 17:31
  • I have tried those solutions, They did not work and I could not understand most of the code (I'm fairly new to React and JS) – SnaccOvenFlour Apr 15 '21 at 17:39
  • I tried using catch, The result is still the same – SnaccOvenFlour Apr 15 '21 at 17:39

1 Answers1

1

Since ajax request will work in asynchronous manner in js, we can make the call as synchrous with async await.

async function isAuthenticated() {
    const authtoken = localStorage.getItem('AuthToken')
    if (authtoken == null) {
        return false
    } else {
        let UserData;
        UserData = await axios.get(`http://localhost:8000/api/token/?token=${authtoken}`).then(function(request) {
          return request.data
        })
        if (UserData.Error == "Token not valid") {return false}
        else {return UserData}
    }
}

# while executing use await
userData = await isAuthenticated()
Kumar KS
  • 873
  • 10
  • 21