How to preload data before rendering react app

2.7k Views Asked by At

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)
            };
        }
    },
2

There are 2 best solutions below

0
On BEST ANSWER

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>
    )
  }
)
0
On

you can use this code for example:

const [text, setText] = useState("")
const [loading, setLoading] = useState();
const fetchdata = () => {
  setLoading(true)
  fetch("youurl is here")
    .then((res) => res.json())
    .then((data) => setText(data.title))
  setLoading(false)
}

and in your component write the conditional:

<div className='App'>
  <button onClick={fetchdata}>Fetch Data</button>
  {loading ? <p>loading</p> : <p>{text}</p>}
</div>

of course, you should use useEffect hook to fetch data