0

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])

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1
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();
         //...
      }
    })();
}, [])

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.