0

I am trying to get a user data from asynstorage to the initial state of redux store but getting a promise instead of value from async storage even after adding async await in a redux store.in the function on a console.log its working fine but when i am trying get its return value it gives me a promise instead of object value.

import AsyncStorage from '@react-native-async-storage/async-storage'
import {createStore , combineReducers , applyMiddleware} from 'redux'
import thunk from 'redux-thunk'
import { userLoginReducer, userRegisterReducer } from './reducers/userReducers'

const reducer = combineReducers({
userLogin : userLoginReducer,
userRegister : userRegisterReducer
})
const getData = async () => {
        const value =  await AsyncStorage.getItem('user');
        if (value !== null) {
            // Our data is fetched successfully
            var newVal =JSON.parse(value)
            console.log(newVal.name)
            return newVal

        }
    

}
const dataFromAsyncStorage = getData().then(res=> {
    console.log(res)
})


const initialState = {
userLogin : {user : dataFromAsyncStorage ?  dataFromAsyncStorage : null} 
}


console.log(initialState)


const middleware = [thunk]

const store = createStore (
    reducer ,
    initialState ,
    applyMiddleware(...middleware)
)

export default store

I want the data to be in the initialstate. please guide me for the same

  • here you can call `const dataFromAsyncStorage = getData();` – Amruth Aug 01 '21 at 09:06
  • 1
    The initial state must be synchronous, so you can't do this. You have to store a temporary initial state, possibly render it as a loading screen, and set a new state when the data was actually returned. – CherryDT Aug 01 '21 at 09:07
  • Also, `dataFromAsyncStorage = getData().then(res=> { console.log(res) })` will be a promise resolving to undefined and not even your value because you aren't returning `res` from your `then` – CherryDT Aug 01 '21 at 09:09

0 Answers0