I am having big troubles using useNavigation() in an interceptor response.
First of all, i had to created a new file where i put my function with the navigation.
NavigateError
import React, {useEffect, useState} from 'react';
import {useNavigation, CommonActions} from '#react-navigation/native';
export const NavigateToLogin = () => {
console.log('ENTERS THE FUNCTION ------------');
const navigation = useNavigation();
navigation.navigate('Indexv2');
}
and then i imported it where i have my interceptor response
import {NavigateToLogin} from './navigateError';
and finally use it.
interceptor response
case 403:
//Alert.alert('Error 403', 'Servidor bloqueado');
NavigateToLogin();
console.warn('Error 403, Servidor bloqueado');
The problem is that i got a invalid hook errors. I dont know how to deal with this issue.
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:
You might have mismatching versions of React and the renderer (such as React DOM)
You might be breaking the Rules of Hooks
You might have more than one copy of React in the same app
Related
I have a React app created with create-react-app.
I'm trying to make a custom hook using Microsoft Authentication Library (MSAL). MSAL has a custom React hook that I want to call from my own custom hook.
When I use a hook (any hook) inside my custom hook in a separate file I get this in the browser:
Warning: 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
// ourhook/index.ts
import { useEffect } from "react";
export const useMsal2 = () => {
useEffect(() => {
console.log("Hello from our hook!");
});
};
// app.tsx
import React from "react";
import { useMsal2 } from "./ourhook";
const App = () => {
useMsal2();
return <div>App</div>;
};
export default App;
If I call
const { instance } = useMsal();
directly from App.tsx everything works fine. It only appears to be a problem if my custom hook is in its own file.
From what I see I'm not violating any hook rules. I'm calling a hook that's calling a hook, and the first call is from a top level component.
I have read other threads here about hooks in hooks, but none of them has an answer that fits this problem.
Have I missed something about hook rules, or what might be causing this?
Okay, I forgot that we tried to have /ourhook as a freestanding project and then copy pasted it into a create react app app.
Some of you were right, it did have its own version of react.
I'm just going to hide under a rock for the rest of the week.
Thanks for all your help! <3
Try to add this comment just above:
import { useMsal } from "#azure/msal-react";
export const useMsal2 = () => {
// eslint-disable-next-line react-hooks/rules-of-hooks
const { instance } = useMsal();
const request = "";
return {
loginRedirect: () => console.log(""),
}
};
I don't know what useMsal looks like, but from what I see, you don't actually violate any hook rule.
I have a NextJS app. I want to add a function that can redirect to any page using nextjs routing.
For example, after finishing signup I want to redirect to a certain page.
If I create this function (reusable everywhere) :
import { useRouter } from 'next/router'
const goTo = (href) => {
const router = useRouter()
router.push(href)
}
I want to add this to my signup Logic, the problem is that I break React Hooks rules :
react-dom.development.js?ac89:14906 Uncaught (in promise) 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:
You might have mismatching versions of React and the renderer (such as React DOM)
You might be breaking the Rules of Hooks
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.
And effectively useRouter is a React Hook, and I'm trying to call it outside a React function, as stipulated here https://reactjs.org/docs/hooks-rules.html it will not work.
How can I then have a routing solution for NextJS to be callable in regular Javascript ?
So If you're using purely React.js (without Next.js on top of it), you can simple do it this way:
Import React from 'react'
export const handleRoutes = (url) => {
const history = React.useHistory()
return history.push(url)
}
Then You'd import this regular js function in any of your react files, like this:
import { handleRoutes } from 'fileName.js'
<button onClick={() => handleRoutes("/routeToBeRedirectedTo")}> Click to redirect </button>
However when using Nextjs I'm not sure that the above way would work. My personal method would be simply implementing this function (in a utility.js file):
export const handleRedirect = (router, url) => {
return router.push(url)}
Then just importing the function & useRouter hook in the file you want:
import { handleRedirect } from "./utility.js"
import { useRouter } from "next/router"
const router = useRouter
Then inside your JSX return statement:
<button onClick={() => handleRedirect(router, "/routeToBeRedirectedTo")}> Click to redirect </button>
And if it's a redirect after sign in/sign up, just simply useEffect like so:
// depends if you're storing your user credentials in your local storage or cookies, this example below would be if your User credentials are stored in localstorage
const user = JSON.parse(localstorage.getItem("user"))
UseEffect(() => {
if (user) return handleRedirect(router, "/routeToBeRedirectedTo")
}, [user])
My App was working fine and suddenly i got this error.
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:
You might have mismatching versions of React and the renderer (such as React DOM)
You might be breaking the Rules of Hooks
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.
import { useContext } from "react";
import jwtDecode from "jwt-decode";
import AuthContext from "./context";
import authStorage from "./storage";
const useAuth = () => {
const { user, setUser } = useContext(AuthContext);
const logIn = (authToken) => {
const user = jwtDecode(authToken);
setUser(user);
authStorage.storeToken(authToken);
};
const logOut = () => {
setUser(null);
authStorage.removeToken();
};
return { user, logIn, logOut };
};
export default useAuth;
All looks fine. except maybe actually importing React
import React, { useContext } from "react";
I know you don't need this for React from React 17, but there's no official statement from react native saying they use the new JSX compiler that doesn't require the import statement
also check the AuthContext file you imported
I'm trying to get some information from my smart contract to display on my React app front page. However, anytime I try to do so I get this error
Server Error
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.
This error happened while generating the page. Any console logs will be displayed in the terminal window.
Call Stack
resolveDispatcher
file:///Users/louiefranchino/Documents/eventsystem/node_modules/react/cjs/react.development.js (1476:13)
useContext
file:///Users/louiefranchino/Documents/eventsystem/node_modules/react/cjs/react.development.js (1484:20)
Html
../../node_modules/next/dist/pages/_document.js (9:873)
processChild
file:///Users/louiefranchino/node_modules/react-dom/cjs/react-dom-server.node.development.js (3353:14)
resolve
file:///Users/louiefranchino/node_modules/react-dom/cjs/react-dom-server.node.development.js (3270:5)
ReactDOMServerRenderer.render
file:///Users/louiefranchino/node_modules/react-dom/cjs/react-dom-server.node.development.js (3753:22)
ReactDOMServerRenderer.read
file:///Users/louiefranchino/node_modules/react-dom/cjs/react-dom-server.node.development.js (3690:29)
renderToStaticMarkup
file:///Users/louiefranchino/node_modules/react-dom/cjs/react-dom-server.node.development.js (4314:27)
renderDocument
file:///Users/louiefranchino/node_modules/next/dist/next-server/server/render.js (2:749)
renderToHTML
file:///Users/louiefranchino/node_modules/next/dist/next-server/server/render.js (54:698)
runMicrotasks
<anonymous>
processTicksAndRejections
internal/process/task_queues.js (94:5)
async
file:///Users/louiefranchino/node_modules/next/dist/next-server/server/next-server.js (112:97)
async
file:///Users/louiefranchino/node_modules/next/dist/next-server/server/next-server.js (105:142)
async DevServer.renderToHTMLWithComponents
file:///Users/louiefranchino/node_modules/next/dist/next-server/server/next-server.js (137:387)
async DevServer.renderToHTML
file:///Users/louiefranchino/node_modules/next/dist/next-server/server/next-server.js (138:610)
This is strange as my code previously worked, however now I get nothing but this error. Here is my code:
import React, { Component } from "react";
import { Card } from "semantic-ui-react";
import factory from "../ethereum/factory";
class EventIndex extends Component {
static async getInitialProps() {
const events = await factory.methods.getDeployedEvents().call();
return { events };
}
render() {
return <div>{this.props.events[0]}</div>;
}
}
export default EventIndex;
If anyone could help me please let me know.
EDIT: Update: I think there is an error with my dependencies or something. When I try to run my previous applications which worked fine. I'm also getting errors on that albeit different errors. I read that this Hook error can display if you have two react packages, how could I go about resolving this?
Here is the full code:
https://github.com/Loustaaa/eventsystem/tree/test
I'm trying to make a thin wrapper to the "jsoneditor" library using a functionnal component. I'm rather new to React and worked so far mainly with hooks. So I tried to adapt the example given by the author of the library to use hooks:
https://github.com/josdejong/jsoneditor/tree/master/examples/react_demo
This is what I came up with so far:
import React, {useRef, useState, useEffect, useCallback} from 'react'
import JSONEditor from 'jsoneditor'
import styles from './JSONEditorReact.module.css'
import 'jsoneditor/dist/jsoneditor.css';
function App(){
const [json, setJson] = useState({some_key:"some_value"})
function onChangeJson(json){
setJson(json)
}
return <JSONEditorReact onChangeJson={onChangeJson} json={json}/>
}
function JSONEditorReact({onChangeJson, json}){
const containerRef = useRef()
const editorRef = useRef() // used as a namespace to have a reference to the jsoneditor object
useEffect(
() => {
console.log("mounting")
const options = {
modes: ['tree','form','view','text'],
onChangeJSON: onChangeJson
}
editorRef.current = new JSONEditor(containerRef.current, options)
return () => editorRef.current.destroy()
},
[] //eslint complains about the missing dependency "onChangeJson" here
)
useEffect(
() => {
console.log("updating")
editorRef.current.update(json)
},
[json]
)
return (
<div className={styles.container} ref={containerRef} />
)
}
export default App;
It works - but eslint complains about onChangeJson being a missing dependency in useEffect. If I add it as a dependency, useEffect runs each time the user inputs something into the json editor. This implies that the user looses focus on the editor each time he enters a character. My understanding is that when it occurs, setJson function of App is called, so App component is refreshed, causing the onChangeJson function to be-reinstanciated, so the first useEffect is rerun, and a new JSONEditor is instanciated.
I had some ideas but they don't seem satisfying:
define onChangeJson with useCallback - issue : I find it daunting to call useCallback each time I want to use my component
pass the setter function setJson of App as the "onChangeJson" property of JSONEditorReact - issue: what if I want to perform more actions than just setting the state in my callback?
Any more relevant ideas to solve the missing dependency issue without running the first useEffect on each input?
Is this a kind of use case where class components are more relevant than functional components using hooks? (the wrapper using class components looks more straightforward than mine, where I had to use a ref to create a namespace to hold my JSONEditor instance)