How to connect a data API to your react app

This is something that seems like it should be obvious and it probably is to those who create websites regularly, however I struggled with it for a bit.  This tutorial from Fullstack React is awesome and helped me figure this out.  The TL;DR version is below.

Use two nodejs servers, one to serve the client application (that can then be bundled by webpack) and one to serve the api in development.  To run these at the same time use the tool concurrently.  Then when you are ready for deployment you can pack the client app (that you built into a static asset with webpack) and then serve it by the api server with this code:

Then you just copy the code to run the api server and client/build folder to your server and run it how you would normally there.  As to a example of how you serve data to your react app here is an example.

Server:

Client:

React Component:

For a more detailed example refer to the article listed above.  This is something I learned recently while improving rallyscores.com.  You can find the source of that site on GitHub.

 

Leave a Reply

Your email address will not be published. Required fields are marked *