Search code examples
reactjsreact-nativeasyncstorage

Fetching from Async Storage and setting it to INITIAL_STATE comes back null


I am currently fetching from async storage in react-native. I am getting data and am able to display it further down in my component such as the profile image etc, but I am also trying to set the INITIAL_STATE of my formData equal to the values im pulling from async storage. I believe the values are not being fetched fast enough when I do so; thus, I'm getting back null values. Any suggestion on how to accomplish this would be extremely helpful. I am trying to wait for the user to not be null, so that I can use the fetched data as my initial form values. My code is as follows:

  const [user, setUser] = useState(null)
  
const INITIAL_STATE = {
    email: user.email //When I set my initial state to the user data; however it is null
  }
const [detailsToUpdate, setDetailsToUpdate] = useState(INITIAL_STATE)

  useEffect(() => {
    console.log('im running')
    handleGetUserDetails()
  }, [])

  const handleGetUserDetails = async () => {
    const details = await AsyncStorage.getItem('userDetails')
    const parsedDetails = JSON.parse(details)
    await setUser(parsedDetails)
    console.log(user) //This comes back as the user data I want to set as my INITIAL_STATE
  }

Here is an example of my input with the initial form value:

 <Input
                value={detailsToUpdate.email}
                autoCapitalize='none'
                autoComplete={false}
                onChangeText={value => {
                  setDetailsToUpdate({ ...detailsToUpdate, email: value })
                }}
              />

Solution

  • You can't do that. It is because there is nothing called as user.email initially. After you have fetched the data you have something called as user which has the property of email. If you just want to put the value of email in the value attribute of input tag just const INITIAL_STATE = { email: "" } also in your onChange do setDetailsToUpdate({ ...detailsToUpdate, email: e.target.value })

    Also you don't need to await setUser(parsedDetails) as setting a state value is an asynchronous.