score:0

Accepted answer

make state isloading : false, then in componentwiilmount() / didmount() set isloading state true. after on fetch sucess reset isloading to false;

componenetwillmount/didmount(){
this.setstate({
isloading: true
})
fetchdata().then(res => this.setstate(isloading: false))
.catch(err => this.setstate({isloading: false}));


render(){
return(
{this.state.isloading ? <loader /> : <component view /> }
)
}

score:0

you also could use react-router-loading to fetch data before switching the page.

you only need to mark routes with the loading prop and tell the router when to switch the pages using the context in components:

import { routes, route } from "react-router-loading";

<routes> // or <switch> for react router 5
    <route path="/page1" element={<page1 />} loading />
    <route path="/page2" element={<page2 />} loading />
    ...
</routes>
// page1.jsx

import { useloadingcontext } from "react-router-loading";
const loadingcontext = useloadingcontext();

const loading = async () => {
    // loading some data

    // call method to indicate that loading is done and we are ready to switch
    loadingcontext.done();
};

Related Query

More Query from same tag