Невозможно достичь переменной - PullRequest
0 голосов
/ 13 июля 2020

Я пытался передать значение переменной userId в мою переменную url в функции getRecipeLiked , но значение не определено. Хотя при консольном журнале userId я получаю значение.

const  AllRecipes = (props) => {
 
   
    const [decodedToken, setDecodedToken] = useState({})

    // store user's id from decoded token
    const userId = decodedToken.id
    console.log(userId); // output: 14
    
    useEffect(() => {

       const getUserId = () => {
            // 1.retrieve the token from localStorage
            const tokenFromStorage = localStorage.getItem('token');
            if(tokenFromStorage) {            
                // 2. retrieve the payload's token
                const base64Payload = tokenFromStorage.split('.')[1]
                // 3. decoded payload's token and parse it so that we can get the user id
                 setDecodedToken(JSON.parse(window.atob(base64Payload)))
                 console.log(JSON.parse(window.atob(base64Payload)));          
            } else {
                return 'not token to parse'
            }
        }
        getUserId()

        const getRecipeLiked = async () => {
            console.log(userId) //output: undefined
            const url = `http:localhost:4000/user/recipeLiked/${userId}`
            console.log(url); // output: http://localhost:4000/user/recipeLiked/undefined
            
            const result = await axios.get(url)
            setrecipeLiked(result.data)
        }
        getRecipeLiked()

     
    }, [response])

Ответы [ 2 ]

0 голосов
/ 13 июля 2020

Поскольку useState является асинхронным, нет гарантии, что у вас будет значение, установленное setDecodedToken в вашем getRecipeLiked. Вы можете изменить useEffect, чтобы он запускался снова, когда у вас есть значение userId, и выполнять вызов getRecipeLiked только тогда, когда он доступен.

    const [decodedToken, setDecodedToken] = useState({})

    // store user's id from decoded token
    const userId = decodedToken.id
    console.log(userId); // output: 14
    
    useEffect(() => {

       const getUserId = () => {
            // 1.retrieve the token from localStorage
            const tokenFromStorage = localStorage.getItem('token');
            if(tokenFromStorage) {            
                // 2. retrieve the payload's token
                const base64Payload = tokenFromStorage.split('.')[1]
                // 3. decoded payload's token and parse it so that we can get the user id
                 setDecodedToken(JSON.parse(window.atob(base64Payload)))
                 console.log(JSON.parse(window.atob(base64Payload)));          
            } else {
                return 'not token to parse'
            }
        }
        // first time through
        if(!userId) getUserId()

        const getRecipeLiked = async () => {
            console.log(userId) //output: undefined
            const url = `http://localhost:4000/user/recipeLiked/${userId}`
            console.log(url); // output: http://localhost:4000/user/recipeLiked/undefined
            
            const result = await axios.get(url)
            setrecipeLiked(result.data)
        }
        // when setState is finished and you have `userId` available. 
        if(userId) getRecipeLiked()

     
    }, [response, userId]) //userId is passed as a dependency so useEffect is run when it changes
0 голосов
/ 13 июля 2020

Вероятно, происходит то, что 'useEffect' запускается до того, как значение будет установлено. Возможно, вы используете его как componentDidMount ().

...