I am trying to call dispatch from inside a non-component function that handles api calls. The structure is as follows:
-MainApp.js
-scripts/
--auth.js
Inside scripts/auth.js it looks like this:
export async function signIn(nav) {
const dispatch = useDispatch();
try {
...
dispatch(setIsAuthed(true));
}
...
}
I call signIn() from and onPress. I am getting an invalid hook call. What am I doing wrong?
CodePudding user response:
Hooks are functions that let you “hook into” React state and lifecycle features from function components
Don’t call Hooks from regular JavaScript functions. Instead, you can:
✅ Call Hooks from React function components.
✅ Call Hooks from custom Hooks
You should import the store
and call store.dispatch
to dispatch an action
CodePudding user response:
The advice from Yilmaz is wrong. DO NOT DO THAT!
You should never import the store directly into the rest of the codebase. Instead, if you really must access the store elsewhere, inject it from the entry point.