Hello my frontend developer friends, today i will be sharing some useful snippets for handling apis on frontend.
Interacting with APIs is a core part of any React application. Whether you're building a blog, a dashboard, or an e-commerce app, you'll often need to fetch data, send data, and secure your requests. This post covers everything from basic fetching to advanced topics like authentication and abort controllers
- I'll be creating my code snippets on Scribbler.live first, which is a fantastic platform that allows you to run a JavaScript Notebook, Online Compiler, and Editor without the need for manual setup.
- Additionally, I am including a link to code snippets that includes all of the code examples so you can open the snippet and run it yourself to see the results.
- I will be using
scrib.show
from scribbler.live, it is equivalent toconsole.log
Lets dive in...
Table of contents
- HTTP Methods
- Types of data fetching
- Fetching a single piece of data
- Query params
- Limit and Skip
- Sort and order
- Authentication and authorization
- Adding a product
- Updating a product
- Deleting a product
- Abort controller
- Reference
HTTP methods
HTTP methods define the action you want to perform on a resource. Types of http methods:
- GET - Fetch data from the server
- POST - Send data to the server to create a new resource
- PUT - Update/replace an existing resource entirely.
- PATCH - Update part of an existing resource
- DELETE - Delete a resource from the server
Types of data fetching
We could fetch the data in 2 ways: Using promises with .then method or using async/await
- Promises - Basic data fetching
// Could be GET or POST/PUT/PATCH/DELETE
fetch('https://dummyjson.com/test')
.then(res => res.json())
.then(scrib.show);
- Async/await - Basic data fetching, Recommended one as it is more cleaner way for asynchronous data fetching.
// Could be GET or POST/PUT/PATCH/DELETE
const fetchData = async () => {
const result = await fetch('https://dummyjson.com/test')
const data = await result.json()
return data
}
const data = await fetchData()
scrib.show(data)
Fetching a single piece of data
We could pass a data id to fetch a single piece of data like "/products/1" where 1 is the product id we want to fetch
// Fetching a single piece of data
const result = await fetch('https://dummyjson.com/products/1')
const data = await result.json()
scrib.show(data)
Query params
Useful when you need filtering, searching, etc. It is passed by adding a "?" symbol at the end of the url slug, it follows key value pair in this format "?key=value" and separated by "&" for passing 2 query params "?key1=value1&ke2=value2"
// Query params - It wills select all phone products their id and brand name
const result = await fetch('https://dummyjson.com/products/search?q=phone&select=brand')
const data = await result.json()
scrib.show(data)
Limit and Skip using query params
These query params could be used to limit the number of results you want, lets say for pagination or want to skip some of the data
// Limit and skip - Will skip first 10 products and fetch next 10 products in the list of 194 products with their title, id and price
const result = await fetch('https://dummyjson.com/products?limit=10&skip=10&select=title,price')
const data = await result.json()
scrib.show(data)
Sort and order using query params
These are used to sort the data from the backend and then sent it to the frontend in either ascending or descending order.
// Sort and order
const result = await fetch('https://dummyjson.com/products?sortBy=title&order=asc&select=title,stock,weight')
const data = await result.json()
scrib.show(data)
Authentication and authorization
- Authentication verifies the identity of the user.
- Authorization determine if an authenticated user has permission to access a resource or perform an action.
// Authentication - headers specifies the content type we are passing to the backend which is json
// body refers to the request body which is used to send data to the backend, in this case username and password values will be used
// to authenticate the user on the backend and send a response accordingly
// Check output here - https://dummyjson.com/docs/auth
const result = await fetch('https://dummyjson.com/auth/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
username: 'emilys',
password: 'emilyspass',
}),
credentials: 'include' // Include cookies (e.g., accessToken) in the request
})
const data = await result.json()
scrib.show(data)
// Authorization - A bearer token which you will get when you do the authentication, this could be used to validate the user on the backend
// Check output here - https://dummyjson.com/docs/auth
const result = await fetch('https://dummyjson.com/auth/me', {
method: 'GET',
headers: {
'Authorization': 'Bearer /* YOUR_ACCESS_TOKEN_HERE */', // Pass JWT via Authorization header
},
credentials: 'include' // Include cookies (e.g., accessToken) in the request
})
const data = await result.json()
scrib.show(data)
Adding a product
POST method is used to add a new data
// Adding product
// headers specifies the content type we are passing to the backend which is json
// body refers to the request body which is used to send data to the backend, in this case title to pass the title of the product we want to add
const result = await fetch('https://dummyjson.com/products/add', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
title: 'BMW Pencil',
/* other product data */
})
})
const data = await result.json()
scrib.show(data)
Updating a product
PUT method is used to update some data with id as 1
// Update a product
// headers specifies the content type we are passing to the backend which is json
// body refers to the request body which is used to send data to the backend, in this case title to pass the title of the product we want to update
const result = await fetch('https://dummyjson.com/products/1', {
method: 'PUT', /* or PATCH */
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
title: 'iPhone Galaxy +1'
})
})
const data = await result.json()
scrib.show(data)
Deleting a product
DELETE method is used to perform a delete operation
// Deleting a product - this will delete the product with id as 1
const result = await fetch('https://dummyjson.com/products/1', {
method: 'DELETE',
})
const data = await result.json()
scrib.show(data)
Abort controller
Sometimes you want to cancel a request in a scenario lets say when a user click a button which makes an api call and then click another button which also makes an api call, in this case, you want to cancel the first button api call and proceed with second api call only. Abort controller helps in this scenario to cancel request which you don't need.
This example is just to show the functionality of abort controller by manully aborting a request, in real world scenarios you will be handling this with some efficient techniques which handles the abort process automatically like react js useEffect hook where the return statement handles the abort process on component unmount automatically.
// Abort controller
const controller1 = new AbortController(); // Controller for first fetch
const controller2 = new AbortController(); // Controller for second fetch
const fetchData = async (url, controller, label) => {
try {
const response = await fetch(url, { signal: controller.signal });
const data = await response.json();
scrib.show(`${label} Success:`, data);
} catch (error) {
if (error.name === 'AbortError') {
scrib.show(`${label} Aborted!`);
} else {
scrib.show(`${label} Error:`, error);
}
}
};
// Call first fetch
fetchData('https://dummyjson.com/products/1', controller1, 'Fetch 1');
// Abort the first call before it completes
setTimeout(() => {
controller1.abort(); // Cancel Fetch 1
}, 100); // Cancel after 100ms
// Start second fetch which will succeed
fetchData('https://dummyjson.com/products/2', controller2, 'Fetch 2');
Reference - Dummy JSON api
I have used this dummy json api in this blog examples, you could checkout this api to learn more about api handling.
Link - https://dummyjson.com/
That's it for this post, Let me know if i could do any improvements in this article. Also, do check Scribbler.live website.
You can contact me on -
Instagram - https://www.instagram.com/supremacism__shubh/
LinkedIn - https://www.linkedin.com/in/shubham-tiwari-b7544b193/
Email - shubhmtiwri00@gmail.com
You can help me with some donation at the link below Thank you👇👇
https://www.buymeacoffee.com/waaduheck
Also check these posts as well

Top comments (0)