0

First of all, considering that the question seems quite obvious did a fair amount of research to find the answer but unfortunately I couldn't. Apologies in advance if this has been asked previously.

I'm currently learning React+Redux and have a pretty simple piece of code:

const AuthRoute = ({ component: Component, ...rest }) => {
  console.log(localStorage.getItem('user')); //undefined
  return (
    <Route {...rest} render={props => (
      localStorage.getItem('user') ?
        <Component {...props} /> :
        <Redirect to={{ pathname: '/login' }} />
    )} />
  )
}

When this code is executed, I'm expected that non-authenticated user will be redirected to the login page. However, for some reason, the inline if check for the localStorage.getItem('user') which resolves to undefined does not provide the expected result.

In addition, I've also tried !!localStorage.getItem('user') which also doesn't resolve to false and do not redirect to the page expected.

However, localStorage.getItem('user') !== 'undefined' works like a charm.

What am I missing here?

Thanks

EDIT:

Condition localStorage.getItem('user') === undefined works fine, but why localStorage.getItem('user') doesn't resolve to a falsy if result itself?

localStorage contents:

Storage {darkyMode: "1", darkyState: "f", user: "undefined", darkySupported: "t", length: 4}
length: 4
darkyMode: "1"
darkyState: "f"
user: "undefined"
darkySupported: "t"
__proto__: Storage

FINAL EDIT:

So before adding the code to plunker to be reviewed by you guys I've added some more logging into my app to ensure I'm definitely not missing something obvious and as always, there was something obvious...

I had this piece of code in my userService:

return axios.post(`${api}/users/login`, {email, password})
    .then(res => onSuccess(res.data))
    .catch(err => console.log(err));
    .finally(user => localStorage.setItem('user', JSON.stringify(user))

I don't know why I thought this was a good idea... Basically, every time user was not recognised, I was returning message property instead of user from the API and this resulted in undefined being set in the localStorage.

Previously, in the onSuccess method, I was only returning the data, now I am performing additional checks on the data and acting accordingly so moving localStorage.setItem('user', JSON.stringify(user)) from .finally into onSuccess method resolved the issue.

Marking @Christian Fritz answer as correct.

Thanks all for the help! :)

11
  • 2
    'undefined' !== undefined. One is a truthy string, the other, the real falsy undefined. Commented Jan 15, 2020 at 21:19
  • Maybe dumb question, but is localStorage.getItem('user') undefined, or is localStorage itself undefined in your code block? Commented Jan 15, 2020 at 21:21
  • @NicholasHirras if localStorage was undefined, OP's code would fail with "Uncaught TypeError: Cannot read property 'getItem' of undefined". Commented Jan 15, 2020 at 21:24
  • 2
    It just means that for some reason, OP set user to undefined in the localStorage, so the key exists, but once serialized, undefined becomes the string 'undefined'. Commented Jan 15, 2020 at 21:26
  • 1
    In your latest edit, you're contradicting yourself. Please include a minimal reproducible example (React is not even needed). Commented Jan 15, 2020 at 21:30

2 Answers 2

1

In the danger of stating the obvious, your storage contains user: "undefined", i.e., a string, so yes, of course, localStorage.getItem('user') !== 'undefined' will work and !localStorage.getItem('user') won't.

I suspect that you are testing for the logged-out case wrong. Make sure to use

localStorage.removeItem('user');

and not localStorage.setItem('user', undefined). It's easy to test that this doesn't work the way one might expect:

> localStorage.setItem('user', undefined)
undefined
> localStorage.getItem('user')
"undefined"
Sign up to request clarification or add additional context in comments.

Comments

0

In your localStorage, there is user key with value undefined which is a string. Given this is the case, you'd have to use localStorage.getItem('user') !== 'undefined' as 'undefined' doesn't resolve as false. The other way is you can removeItem() when starting the application / user logs out

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.