score:0

this is how i usually implement things when it comes to http requests.

this is assuming that you're not using server side rendered (ssr) service like next.js, where you want the data to be fetched before the page is even rendered, then you would use a different approach.

otherwise you could show a loading animation or just show a blank screen until the data is loaded.

click the "run code snippet" button below to see it work.

// main.js

const { usestate, useeffect } = react;

const app = () => {
  const [loading, setloading] = usestate(true);
  const [error, seterror] = usestate(null);
  const [data, setdata] = usestate(null);
  
   useeffect(() => {
    /*
    stackoverflow not letting me do async/await so doing a promise
    */
    fetch('https://jsonplaceholder.typicode.com/todos/1')
    .then(response => response.json())
    .then(json => {
      setdata(json);
      setloading(false);
    })
    .catch(error => {
      console.log('error', error);
      seterror(error);
      setloading(false);
    });
   }, []);
  
  return <div>
    {loading 
      ? <p>loading...</p> 
      : <div>
        {error 
          ? <div>{json.stringify(error)}</div>
          : <div>loaded <br />{json.stringify(data)}</div>
         }
      </div>}
  </div>
}

reactdom.render(<app />, document.queryselector('#root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>


<div id="root"></div>

score:0

since the call to your api is async you will need to wait for the call to be finished to show your app, useeffect is a good way to do it, but you will need to make some changes in your code to work.

i see that you are handling all the state variables separately but some of them depend on each other, for this cases is better to use an object so you can be sure all the properties are updated at the same time and also to know if you have already the needed data to show your app

// show your app until this is not null
const [state, setstate] = usestate(null);

// set all the state variables at the same time
useeffect(() => { axios.get(url).then(config => setstate(config)) }) 

if(!state) return <div>loading...</>

return <div>app</div>

another alternative is to use another state variable to control if you should show your app or not

// all your state variables
const [state, setstate] = usestate(null);
.
.
const [isloading, setisloading] = usestate(false);

// set all the state variables at the same time
useeffect(() => { 
  setlisloading(true); 
  axios.get(url).then(config => {
    setisloading(false);
    setstate(config);
  )
}) 

if(isloading) return <div>loading...</>

return <div>app</div>

Related Query

More Query from same tag