How to retrieve a data from API or Firebase before rendering anything to the user in React?

I want to retrieve data from Firebase and then update it to redux and render it to the user. Can we have conditional rendering in App.js?

If am retrieving a data in HomePage.js (a component) and updating it to redux and displaying it. Then when the user navigates to another page Orders.js or MyProfile.js I get the data from redux using useSelector and displaying it. But if the user visits a Orders.js or MyProfile.js first the data is not retrieved yet since the user didn't visit HomePage.js.

I can now retrieve the data in App.js and use conditional rendering to hold the user from viewing other screen by rendering a loading screen. Is this a good practice?

How to get data universally for all pages before rendering anything to the user?. Hope I made the question clear.

2 answers

  • answered 2021-05-17 05:20 Matthew Kwong

    Usually, the best practice is to load the page anyway regardless of whether the data is ready. Yet, in case the data is NOT ready, display the skeleton of the page similar to this: enter image description here

    Then fetch the data in the useEffect hook and do a setState once the data is received. After that, display the intended component.

    e.g.

    const Videos = () => {
      const [videos, setVideos] = useState(new Array(5));
      const [loading, setLoading] = useState(true);
    
      useEffect(() => {
        fetch('/api/videos')
          .then(response => response.json())
          .then(videos => setVideos(videos))
          .finally(() => setLoading(false))
      }, []);
    
      return (
        <Container>
          {videos.map(video => loading
            ? <Skeleton />
            : <Video video={video} />
          )}
        </Container>
      );
    };
    

    Note, with the upcoming concurrent mode (no ETA yet, but it has been discussed for a long time). The practice will be changed drastically.

  • answered 2021-05-17 05:22 Jeel

    Yes it's completely good practice. Since if there's no any indicator of loading then user might thought that his/her data is deleted. If the app requires that data to make it intractable for user, then the wait is necessary.

    You can use conditional rendering like ... data !== undefined ? renderStuff() : loadingIndicator()

    You can use react-activity for animated loading indicators.

    You can get all your data in main component like App and use useEffect hook to call the server for data. you can use async Actions to call APIs.

    Hope this answered you questions.