reactjspreloadingreact-location

How to preload data before rendering react app


i use React location library. Want to get token from cookie if it exist then send it to server to check if it is active. My question is how i can do this once before rendering app regardless of route?

i`ve tried something like this but it works only for specific route

    {
        path: '/',
        element: () => import('../pages/Main').then(mod => <mod.default />),
        loader: async () => {
            return {
                user: await fetchResource('user', {}, true)
            };
        }
    },

Solution

  • In App.js you could do something like this

    const [ready, setReady] = useState(false);
    useEffect(()=>{
      // fetch your token and verify
      setReady(true)
      },[]);
    
    return (
      {
        ready ? (
          // Your app components here
        ) : (
           <div> Loading .... </div>
        )
      }
    )