2

Attempting to create a Context, and need to navigate triggered by reading local storage.

I can understand the error that it doesn't allow to use useNavigate() outside a <Router>, but what alternative can I use for this?

Code:

const ChatContext = createContext();

const ChatProvider = ({ children }) => {
    const [user, setUser] = useState()

    const navigate = useNavigate();

    useEffect(() => {
        const user = localStorage.getItem('userInfo')
        if (user) {
            setUser(JSON.parse(user))
        } else {
            navigate('/login')
        }

    }, [navigate])


    return <ChatContext.Provider value={{ user, setUser }}>{children}</ChatContext.Provider>

}

Error:

> Error: useNavigate() may be used only in the context of a <Router>
> component.
> 
> The above error occurred in the <ChatProvider> component:
> 
> ChatProvider@http://localhost:3001/static/js/bundle.js:733:11
> 
> Consider adding an error boundary to your tree to customize error
> handling behavior. Visit https://reactjs.org/link/error-boundaries to
> learn more about error boundaries.
nathan liang
  • 1,000
  • 2
  • 11
  • 22
Anupam Arya
  • 169
  • 1
  • 1
  • 12
  • Can you show me how are you using the ChatContext Provider? Looks like you are using it outside of the Router so it doesn't have access to the router context – Link Strifer Mar 29 '22 at 03:25
  • `import { BrowserRouter } from "react-router-dom"; import ChatProvider from './context/ChatProvider'; ReactDOM.render( , , document.getElementById('root') );` – Anupam Arya Mar 29 '22 at 03:30
  • You currently have `` on the outside, and `` inside of it. Swap the order so that the router is on the outside – Nicholas Tower Mar 29 '22 at 03:31
  • Can you share your `app.js` – Dharmik Patel Mar 29 '22 at 04:29
  • Does this answer your question?https://stackoverflow.com/questions/70491774/usenavigate-may-be-used-only-in-the-context-of-a-router-component – Lin Du Mar 29 '22 at 09:15

0 Answers0