0

I'm trying to save Login state when user successful loged in, they will bring to HomePage instead of LoginPage using Async Storage but it did'nt work, i tried to log the value but it did'nt work , too

Here is the code

Async Storage ( i use Community)

function* SaveToAsyncStorage(data) {
    try {
        AsyncStorage.setItem(
            'data',
            JSON.stringify({
                username: data.username,
                password: data.password
            })).then((data) => {
                console.log(data)
            })
    } catch (e) {
        console.log('error save to Storage');
    }
}

Saga part

function* loginSaga(action) {

    const getJson = yield call(requestGetUser)
    const getJsonUsername = getJson.username
    const getJsonPassword = getJson.password

    if (action.data.username === getJsonUsername && action.data.password == getJsonPassword) {
        console.log('saga login success')
        yield put({type: 'LOGIN_SUCCESS'})
        SaveToAsyncStorage(action.data)
    )


    }
    else if (action.data.username !== getJsonUsername || action.data.password == getJsonPassword) {
        console.log('wrong username or password')
        Alert.alert(
            'Login Status',
            'Wrong username or password',
            [
                {text: 'OKeyy', style: 'cancel'}
            ]
        )
    }

}

And use it in LoginMain

useEffect(async () => {
        try{
            const value=await AsyncStorage.getItem('data')
            if(value!==null){
                navigation.navigate('Home')
                console.log(value)
            }
        }catch(error){
        }
    })

But console print nothing ! Feel like Async Storage never exisited in my code, How can i use Async Storage or make it work, thank a lot

Lê Quốc Khánh
  • 545
  • 1
  • 6
  • 20

2 Answers2

1

Are you already tested a getItem after AsyncStorage.setItem on SaveToAsyncStorage, and I suggest you to use AsyncStorage.setItem as async function to be sure

1

Try to separate your async function from useEffect to another function. Then in useEffect try to call that. As your implementation,your function returns a promise and useEffect doesn't expect the callback function to return Promise, rather it expects that nothing is returned or a function is returned. Exampe :

useEffect(() => {
  const func = async () => {
    try{
        const value=await AsyncStorage.getItem('data')
        if(value!==null){
            navigation.navigate('Home')
            console.log(value)
        }
    }catch(error){
    }
  }
  func()
},[])
Vu Dang
  • 21
  • 3