Home > OS >  How to update state on App start in react native
How to update state on App start in react native

Time:08-02

I am trying to read from the AsyncStorage and update my store ( using easy-peasy ) on app start. My thought process was to call fetch the data from AsyncStorage using useEffect with the second argument of an empty array to only fetch once on app start and update the store with that value using an action. But that doesn't work i get the error invalid hook call. Any insights on how to solve this or what the correct approach would be are appreciated !

App.ts

export default function App() {
  useEffect(() => {
    readData();
  }, []);
    return (
      <StoreProvider store={store}>
        <SafeAreaProvider>
          <Navigation />
          <StatusBar />
        </SafeAreaProvider>
      </StoreProvider>
    );
}


// This needs to be called when app is started
const readData = async () => {
  try {
    const secret = await storage.getItem('secret');

    const initializeState = useStoreActions(
       (actions) => actions.initializeState
    );

    initializeState({
       payload: {
        secret,
       },
     });
    console.log("executed action")
  } catch (e) {
    console.log('Failed to fetch the input from storage', e);
  }
};

STORE

  initializeState: action((state, payload) => {
    state.secret = payload.secret
  }),

ERROR

Failed to fetch the input from storage [Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.]

CodePudding user response:

export default function App() {
  useEffect(() => {

setTimeout(()=>{ // add setTimeout() may be this work for you
  readData(); 
},500)
  
  }, []);
    return (
      <StoreProvider store={store}>
        <SafeAreaProvider>
          <Navigation />
          <StatusBar />
        </SafeAreaProvider>
      </StoreProvider>
    );
}


// This needs to be called when app is started
const readData = async () => {
  try {
    const secret = await storage.getItem('secret');

    const initializeState = useStoreActions(
       (actions) => actions.initializeState
    );

    initializeState({
       payload: {
        secret,
       },
     });
    console.log("executed action")
  } catch (e) {
    console.log('Failed to fetch the input from storage', e);
  }
};

CodePudding user response:

You need to move you readData function into the App component since you're using a hook (useStorageActions) inside that function and you can only call hooks at the top level. You should take a look at the rules of react hooks.

  • Related