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.