'Page not reloading on navigate("/") (svelte-routing)
I am working on a website and there for using Svelte and the svelte-routing library . The svelte-routing library has a method called navigate(path). I use this function on a click of a button and it works perfectly. But in my routeHandling.js file its not working as expected. I can see that it sets the url in the browser but its staying on the same page, so I have to press F5 (reload the page) to load the page.
import {navigate} from "svelte-routing";
import * as axios from "axios";
export function checkLoggedIn() {
console.log("checkLoggedIn is now getting executed");
if (window.location.pathname !== "/" && window.location.pathname !== "/registration") {
axios.default.get('http://127.0.0.1:5000/user', {
headers: {
'Authorization': `${localStorage.getItem("token")}`
}
}).catch(response => {
navigate("/");
});
}
}
Thanks in advance!
Solution 1:[1]
you need to use the navigate
method inside a svelte component. Try creating a method that calls the checkLogggedIn()
method from your svelte component and does navigate()
on successful return.
import checkLoggedIn from "./router";
import {navigate} from "svelte-routing";
const checkUser = async () => {
let res = await checkLoggedIn();
if (res.status === 200) {
navigate('/')
} else {
navigate('/login')
}
}
something like this should work. you'll want to wait for the response before navigating so I made it an async function
Another thing you will want to check is if you're using the -s or -single
flag when you start svelte. Check your NPM scripts.
Just in case you're new to svelte-routing:
you need to add a Router
to your App, and create paths with the componenets to be rendered on them. like this
<Router>
<Route path="home">
<Home />
</Route>
<Route path="about">
<About />
<Route />
</Router>
where the <Home />
and <About />
are components you would like to render on those routes.
Solution 2:[2]
You can use location.replace("/")
to reload and get all the components.
But you are removing the history for the first page so you can't go back.
const checkUser = async () => {
let res = await checkLoggedIn();
if (res.status === 200) {
location.replace("/");
} else {
navigate('/login')
}
}
or you could do a location.reload();
after navigate to keep the history
if (res.status === 200) {
navigate('/')
location.reload();
} else {
navigate('/login')
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Donkey Coder |