Adding loading indicators

One more improvement that you could make is to add loading indicators as we did with the Vue version.

Doing so is rather easy with React and react-bootstrap. One way to do so is to add two state variables to hold the loading state for artists and songs.

Here's an example with artists:

const [artistsLoading, setArtistsLoading] = useState(false); 

With this defined, you could set the state to true within the search function just before sending the GraphQL query and back to false once Promise has settled.

Here's an example taken from the final code of LyricsFinder V2:

setArtistsLoading(true); 
apolloClient.query<FindArtists, FindArtistsVariables>({ 
    ... 
}).then((result: ApolloQueryResult<FindArtists>) => { 
    ... 
}).finally(() => setArtistsLoading(false)); 

With this logic in place, displaying and hiding the loading indicator is simply a matter of using conditional rendering again in the JSX code.

Here is how you can implement this:

<Accordion.Toggle as={Card.Header} variant="link" eventKey="0"> 
    <h3>Artists</h3> 
    { artistsLoading && 
        <Spinner animation="border" role="status"> 
            <span className="sr-only">Loading...</span> 
        </Spinner> 
    } 
</Accordion.Toggle> 

As you can see, we have used the Spinner component of react-bootstrap and wrapped it into a conditional expression.

This is the recommended way to write conditional expressions in JSX. The idea is that if artistsLoading is truthy, then Spinner will render.

You can, of course, apply the same logic for the songs list, as we did in the final version of the code:

{ songsLoading ? ( 
    <Spinner animation="border" role="status"> 
        <span className="sr-only">Loading...</span> 
    </Spinner> 
) : null} 

In this case, just to show an alternative way, we've used a ternary expression. This other way of writing conditional expressions in JSX is more useful when you actually have two alternatives to render.

These are all just baby steps; there are many more things to improve. That is the whole difference between a small prototype like those in this book and real-world applications!

Following are some references:

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.227.190.93