App.js:
function App() {
PreProcess();
const user = useSelector(selectUser); // user initialized to null
return user ?
(
<p>{user}</p>
)
:
(<p>Authenticating and Authorizing</p>)
}
export default App;
preProcess.js:
export const PreProcess = async () => {
await readEnvVars(); // read env vars in local json file
Auth(); // need environment variables for authentication and authorization
}
auth.js
export const Auth = async () => {
const dispatch = useDispatch();
// some logic for authentication and authorization to get the user
dispatch(setUser(userId));
}
Received error
Uncaught (in promise) Error: Invalid hook call. Hooks can only be called inside of the body of a function component.
at auth.js:
const dispatch = useDispatch();
Why do I get this error and how to solve this?
Hooks cannot be called inside plain javascript functions, only within another hooks, or in function components.
Reference: https://reactjs.org/docs/hooks-rules.html
I solved this by moving the const dispatch = useDispatch(); up to App.js and pass the dispatch var as an argument to the method needs it.