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! :)
'undefined' !== undefined. One is a truthy string, the other, the real falsyundefined.localStorage.getItem('user')undefined, or islocalStorageitself undefined in your code block?localStoragewas undefined, OP's code would fail with "Uncaught TypeError: Cannot read property 'getItem' of undefined".usertoundefinedin the localStorage, so the key exists, but once serialized,undefinedbecomes the string'undefined'.