I’ve implemented protected routes in my React app via React Router V6. Whenever I attempt to login, I don’t get redirected to /home, which is being done by the useNavigate hook in React Router. However, after pressing login I can manually enter /home into the URL and I get redirected. I checked session storage and the token and user are being stored, which is what I’m using for the protected routes. So it’s just something with this useNaviagte hook. It works perfectly fine locally so I’m guessing it’s something with my _redirects file. If someone could help that would be great!
URL: Vite + React + TS (main–elaborate-cajeta-7e14e8.netlify.app)
Github Repo: GitHub - welshy557/chat-app-frontend
No, it is nothing to do with the
_redirects file in the repository. As you are deploying an SPA, the only line that needs to exist is the one in the file.
So it is entirely due to something in the code.
Interesting to note in the
useNavigate documentation it suggests using
redirect for loaders instead.
Hi thanks for the reply. Turns out it was happening both locally and on the server. I was controlling the stored user and token in state and session storage via a custom hook. On the initial load, there is no stored user or token. So the only route available is the login screen. Once you hit login, the state updates but it does not rerender App.tsx where the conditional routing occurs. I ended up refactoring the stored user and token into context and wrapping the provider around all the routes so the whole app rerenders when the token and user changes. You can see that in the latest commit of my repo if you’re interested. This is the first time I’ve used context so please provide some tips if you have any
Second last commit now. I didn’t save a file
When it comes to React, my only tip is to not use it.
To each their own I guess