Dmitriy
Dmitriy

Reputation: 33

pass token using useEffect and AsyncStorage in React Native

I start to use React Native, and should use AsyncStorage instead of LocalStorage

But I can't deal with async in useEffect and AsyncStorage, because token sets after fetch send everything. Help me please with that

const [tkn, setTkn] = useState('')

const getData = async () => {
    try {
        const value = await AsyncStorage.getItem('token')
        if(value !== null) {
            setTkn(value)
        }
    } catch(e) {
        
    }
}

useEffect(() => {
    AsyncStorage.getItem('token').then((value) => {
        if (value) {
            setTkn(value)
        }
    });


    fetch('http://127.0.0.1:8000/home', {
        method: "GET",
        headers: {
            'Content-Type': 'application/json',
            Accept: 'application/json',
            'Token': tkn
        }
    })
        .then(function (response) {
            if (response.status >= 200 && response.status <= 299) {
                return response.json();
            } else {

            }
        })
        .then(funds => {
            ///
        }).catch(function (error) {
            
        })
}, [history])

Upvotes: 0

Views: 955

Answers (2)

Dmitriy Mozgovoy
Dmitriy Mozgovoy

Reputation: 1597

useEffect(() => {
    (async()=>{
      const token = await AsyncStorage.getItem('token');
      setTkn(token);
      const response= await fetch('http://127.0.0.1:8000/home', {
        method: "GET",
        headers: {
            'Content-Type': 'application/json',
            Accept: 'application/json',
            'Token': token
        }
      });
      if (response.status >= 200 && response.status <= 299) {
         const json= await response.json();
         //...
      }
    })();
}, [])

Upvotes: 1

Kai
Kai

Reputation: 2599

I would recommend creating two effects: one to fetch the token from storage, and one to make the API call.

The first effect will fire when the component mounts (pass a [] as the useEffect dependencies) and the second will fire when the token changes (pass [tkn] to that useEffect, and check to make sure that the token has a non-empty value).

This way, you won't have to worry about chaining all of your async logic together.

Upvotes: 1

Related Questions