Developing your toolkit — AJAX calls
Having options…Now that is the goal!
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.
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.
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.
Limitations seem real when we lack faith and belief. With faith and belief, anything is possible.