Home > Software design >  How to get React page to render loading page
How to get React page to render loading page

Time:09-02

So I have created a method inside of the App React component so that when someone goes to save, the DOM switches and renders the loading page, process the POST request, and then re-renders the original page.

  loadingPlaylist() {
    // Using pending variable to determine what to do next //
    
    let pending = false;
    
    if(pending === true) {
      return (
        ReactDOM.render(<LoadingScreen />, document.getElementsByClassName('app'))
      )
    }
    
    // trackCheck is checking if there is something in the playlist to save, if not alert should pop up.
    // If there is something to save, loading pending is changed to true and LoadingScreen renders
    const trackCheck = () => {
      if(!this.state.playlistTracks.length) {
        return alert('There are no tracks in your playlist dude');
      } else {
        pending = true;
      }
    }

    // Performs functions in order to run check. Checks if something is there to save, saves the info, 
    // then checks if the area is empty
    const isLoading = () => {
      trackCheck();
      this.savePlaylist();
      trackCheck();
    }

    isLoading();

    //Method is saved to a event listener
  }

I know if is probably garbage for a React App and nothing is currently working as intended. Need help to do this correctly.

CodePudding user response:

You don't need to manually interact with the DOM yourself. That's what React is for.

If you want to perform certain actions based on the lifecycle of your app then you can look at which functions React exposes.

In the case where you need to watch for updates what would help you is the useEffect hook (presuming you're using the latest functional components, if not then you need to look at the lifecycle methods on class components).

I suspect however you don't need the above. You can probably create a local loading state using Reacts useState hook. Then once your POST request is made you can set the loading state to true. Once your request is succesful you can set your loading state back to false. This state should conditionally render your component.

CodePudding user response:

You can add this line inside your jsx page (replace YourComponent):

{pending ? <YourComponent /> : <LoadingScreen />}
  • Related