DEV Community

nick-raym
nick-raym

Posted on

How to use a get/fetch command to GET data

-Set up a db.json file in the same file as your index.js file (your Javascript file).
-Add different data into your db.json file with an array of objects.
Example/Syntax:

{

    "colors":[
        {
            "id": "1",
            "name": "Green",
            "shade": "Forest"
        },
        {
            "id":"2",
            "name":"Mauve",
            "shade":"Taupe"
        }

    ],

    "dogs":[
        {
            "id": "1",
            "name": "Benji",
            "species": "Border Collie Mix",
            "age":4
        },
        {
            "id": "2",
            "name": "Apollo",
            "species": "Husky",
            "age":3
        }

    ]

}
Enter fullscreen mode Exit fullscreen mode

-Create the ability to open your server to host your database. type in terminal and use -g to globally install --> npm install -g json-server
-Open your db.json on a local server: json-server Relative Path/db.json
-If the db.json is in the same folder then simply type json-server db.json.
-Click on the data you want to use and copy the URL.
-Open your javascript file and type fetch(URL). Don't end the line with a semicolon or else the rest of the code won't work.
-if you used this data set then the URL should look like this: http://localhost:3000/colors. The number of the port may look different.
-On the next line type,

.then(response => {
    return response.json()
})
Enter fullscreen mode Exit fullscreen mode

This allows us to use the response from the fetch request as an object that we can call.
-Next, type,

.then(colors => {
//Your code here
})
Enter fullscreen mode Exit fullscreen mode

Here, you can access your data by using basic JavaScript to find the correct value in the object. A way to see that this works is to try to log your data into the second .then function.

console.log(colors)
Enter fullscreen mode Exit fullscreen mode

This will give you an array of your colors with their keys and values. From here you can use your data to append onto your page or anything you want.

Top comments (0)