Developing your toolkit — AJAX calls

Having options…Now that is the goal!

Middleware Setup

As I continue to work on tutorials to learn and keep my wits up, I continue to run into new opportunities. I had imported my apiRouter to my controller file and implemented the ‘use’ method to access it within my application.

Project files and directories of concern…
Middleware setup…

Now within my ‘api’ directory I had created a file to handle the URL requests. This file imports express library to use the Router method and the JSON file I created with test data. In the below red box, I use the ‘get’ method to handle requests for the URL ‘/contests’ and response back with an object with the testData. With that set up, it was time to bring the information into the React component via an AJAX (i.e. Asynchronous JavaScript and XML) call.

Route Setup

Within the React component, we typically run the ajax call within the ‘componentDidMount()’ method. This is one of the lifecycle events of a React component. But, first I had to set the state as an empty array because the html would render prior to receive the data back from the ‘api’. Once this was set, I had a choice to use the axios library to handle this call or use a the fetch method. Both handle the http request, but one adds more to the project when a simple function will do. Remembering what my instructor suggested about simplicity, I decided to use the ‘fetch’ method. Everything worked out perfectly.

Component Settings

Setting the State of the ‘contest’ key…
Using the fetch method for the ajax call…

The fetch method requests the api/contests URL and I am returned a string response that I convert to JSON with the .json() method. Once this has been completed, I am then able to set the new state of the ‘contests’ key to a key value of the response.contests. This renders the data and that is it.


I have nothing against axios, but it is always nice to have more than one way to solve a problem.

Inspirational Quote:

Limitations seem real when we lack faith and belief. With faith and belief, anything is possible.