Does practice make perfect or practice make permanent? I was quickly able to answer 'this' after learning Javascript in just three weeks.
Excited to get started, I began coding my single page application in one index.js file. This felt very unnatural. When that became too overwhelming I started to use es6 classes to take advantage of javascript's object oriented programming. This was not an easy task. I separated all my objects into source files and made sure they were included in the html body. The most tedious part of the project was making sure the data was being fetched correctly after abstraction. To accomplish this I had to become best friends with Ruby's pry and Chrome's debugger. Let's break it down troubleshooting a front end and a backend using my sports model. Upon page load the scripts are loaded in and the apiCall method fetchSports() is executed. This calls on the apiCall class that I abstracted to handle AJAX fetch requests.
Inside the method is a fetch that triggers a get request to the rails server @ localhost:3000/sports through the variable sportUrl.
I used binding.pry here to see the params being sent from the fetch request and I'm able to see that rails has routed the request to my index action with the following params. So far so good.
From here I set a local variable sports equal to Sport.all an active record method to pull all sports from the database. The controller then calls on fastJSON's sport serializer. This class then wraps the sports variable into a big string to be sent back to the front end. Whats sent is a fetch promise with a response object. The response object holds all of data from the backend sports model. I used debugger here in the fetch to see the data data['data']
. Now it's time to compare the response data to the data from localhost:3000/sports.
Sports Fetch:
Local Host:
Chrome Console:
Looking at Chrome console the array of sports objects from the promises response mirror the backend data. We can see that the objects are ready to be iterated over, instantiated/deconstructed and then rendered on the dom.
Instantiation:
Load:
Render:
Since the data matched up I'm able to focus on creating the next controller, model and view. Then the cycle repeats. When I originally started the project I constantly had to double check permitted params, and serializer attributes. It's also worth noting that formatting your api endpoint data or seed data will greatly benefit structure for fetches. Using debugger helped make sense of the fetch request documentation I was learning. This also helped me understand how rails and javascript are communicating. Theres a lot of moving parts with single page applications. If you are able to practice working with the data each step of the way, you can manipulate it to your needs. Practice makes permanent. Take the time to practice using the tools given and you can troubleshoot anything.
Cover Image by Milada Vigerova from Pixabay
Top comments (0)