Why would I want to get data from my backend and manipulate it on my frontend..ew? Well not ew. In this day in age, we want to have dynamic applications that give users a grand experience. We don't want stale, static applications that don't change. This is why we use and manipulate data (our backend) so that we can make and persist changes on the fly. Today, we will just be looking at how to "GET" that data.
So I'm going to assume you already have a backend database that you would like to work with (using Rails as your API), and your here to find out how to connect it to your frontend and work with that data. Cool? Cool.
Once you have your super cool Rails database that you are ready to work with, do ahead and start up your server. Check out that data that you are gonna work with.
(This will be at the INDEX route sticking to restful routes, that should already be set up)
Yay some nice data. But how do we get this data in out frontend. Well lets move over to a JS file we've named
We are going to use this file to get that super crazy amazing cool data from our database, this is where FETCH comes into play!
Inside of your
Cool. We're done.
Just kidding. This method however, is the key to getting out data from our back end. The fetch method takes two arguments. The first is a URL (Yes! For those who guessed, our database URL) and the second is an object (we wont worry about that right now). What we are going to do is put the URL of our database as the first argument in the fetch method(as a string).
If we were to
console.log() this we would get the following in return:
What is this weird thing..a "Promise". This isn't the data that we want back. Well essentially a
So what can we do with this Promise to get the data that we need? Well once we get this response
.then we want to get our response. If you got the hint, we are goin got use
.then on our fetch. This will give us back a response.
If we console log this we get back:
Great we are almost there! With this new Promise (console log what we just did, we get back a promise again) we can
.then get back the data we need. Got the hint again? We use
.then again, but this time we get back:
In the console:
We get back and Array of Data!