K
K
KGZVER2020-07-10 13:25:41
JavaScript
KGZVER, 2020-07-10 13:25:41

How to solve this problem with if/else?

When entering the page, I want to make a fetch request, provided that the constToken variable has a value. But for some reason the request works even when constToken == false.

React.useEffect(() => {
        const getToken = localStorage.getItem('token')
        if(getToken !== '') {
            changeValue('token', getToken)
            fetch('http://localhost:1717/profile', {
                method: 'GET',
                headers: { 'X-Auth': `${getToken}` },
            }) 
            .then(function (response) {
                return response.json()
            })
            .then(function ({data}) {
                setId(data.id)
                changeValue('profile', data)
            })
        }
        
    }, [changeValue, changeProfile, login])

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Aetae, 2020-07-10
@KGZVER

Only strings localStorageare stored in . If you do so , then when you get not , but the result of casting to a string, i.e. However , it is also true, because the comparison is without type casting. localStorage.setItem('token', false)localStorage.getItem('token')''false'false'.
false !== ''!==

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question