title: How can I get data from AsyncStorage and add it to initial state when using useReducer?
body: <p>I'm using <strong>useContext</strong> &amp; <strong>useReducer</strong> from Hooks &amp; <strong>AsyncStorage.setItem</strong> in <strong>useEffect</strong> to save the data whenever state gets updated. On app reload I want to make sure to get saved data using <strong>AsyncStorage.getItem</strong> and add it to the initial state.</p>
  
  <p>I tried to add init function with async as the third property to useReducer but still, it's not replacing initial data with received data. Please go through below code and help.</p>
  
  <p>Thank you in advance!</p>
  
  <p>Current code where I can save data to AsyncStorage</p>
  
  <pre><code>  const [user, dispatch] = useReducer(userReducer, {});
  
    useEffect(() =&gt; {
      AsyncStorage.setItem('user', JSON.stringify(user))
    }, [user]);
  
    return(
      &lt;UserContext.Provider value={{user,dispatch}}&gt;
        {props.children}
      &lt;/UserContext.Provider&gt;
    );
  }
  </code></pre>
  
  <p>Below is the code I tried, but unable save existing data as initial data.</p>
  
  <pre><code>const getUser = async function() {
    const userData = await AsyncStorage.getItem('user')
    console.log("parse");
    console.log(userData);
    console.log("parsed data");
    console.log(JSON.parse(userData));
    return userData ? JSON.parse(userData) : {};
  }
  
  export const UserContext = createContext();
  
  const UserContextProvider = (props) =&gt; {
    const [user, dispatch] = useReducer(userReducer, {}, getUser);
  
    useEffect(() =&gt; {
      console.log("context");
      console.log(JSON.stringify(user));
      AsyncStorage.setItem('user', JSON.stringify(user))
    }, [user]);
  
    return(
      &lt;UserContext.Provider value={{user,dispatch}}&gt;
        {props.children}
      &lt;/UserContext.Provider&gt;
    );
  }
  </code></pre>