Aplicación.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;preProceso.js:
export const PreProcess = async () => { await readEnvVars(); // read env vars in local json file Auth(); // need environment variables for authentication and authorization }autenticación.js
export const Auth = async () => { const dispatch = useDispatch(); // some logic for authentication and authorization to get the user dispatch(setUser(userId)); }error recibido
Error no capturado (en promesa): Llamada de gancho no válida. Los ganchos solo se pueden llamar dentro del cuerpo de un componente de función.
en auth.js:
const dispatch = useDispatch();
¿Por qué me sale este error y cómo solucionarlo?
Los ganchos no se pueden llamar dentro de funciones simples de javascript, solo dentro de otros ganchos o en componentes de funciones.
Referencia: https://reactjs.org/docs/hooks-rules.html
Resolví esto moviendo const dispatch = useDispatch(); hasta App.js y pase la variable dispatch como argumento para que el método lo necesite.