Explore snippets
Discover reusable code snippets, examples, fixes, and ideas shared by developers, students, and teams.
Modern JavaScript User Loader
Loads and manages users asynchronously from an API, providing methods to find users by ID and render the user list in the DOM.
let users = [];
let isLoading = false;
class User {
constructor(id, name, email) {
this.id = id;
this.name = name;
this.email = email;
}
getDisplayName() {
return `${this.name} (${this.email})`;
}
}
Fetch Active Users
Fetches users from an API and returns only those who are active using async/await and ES6+ syntax.
const fetchActiveUsers = async (url) => {
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const users = await response.json();
Debounced Search Input Handler
Implements a debounced search input handler that delays API calls until the user stops typing for 500ms, reducing unnecessary requests.
function debounce(func, delay = 300) {
let timeout;
return function (...args) {
clearTimeout(timeout);
timeout = setTimeout(() => {
func.apply(this, args);
}, delay);
};
}
Infinite Scroll with IntersectionObserver
Load the next page when a sentinel approaches the viewport and prevent duplicate requests.
const sentinel = document.querySelector('[data-load-more]');
let page = 1;
let isLoading = false;
let hasMore = true;
const observer = new IntersectionObserver(
async (entries) => {
const entry = entries[0];
Typed JSON Fetch Helper
Wrap fetch with JSON parsing, typed responses, and useful HTTP error messages.
type ApiErrorBody = {
message?: string;
};
export async function fetchJson<T>(
input: RequestInfo | URL,
init?: RequestInit,
): Promise<T> {
const response = await fetch(input, {
...init,
headers: {
Accept: 'application/json',
Async Generator for Paginated API Data
Iterate through paginated API responses without loading every page into memory.
type Page<T> = {
items: T[];
nextCursor: string | null;
};
export async function* paginate<T>(
buildUrl: (cursor: string | null) => string,
): AsyncGenerator<T, void, void> {
let cursor: string | null = null;
do {
Process Mixed Results with Promise.allSettled
Run independent asynchronous tasks and keep both successful and failed outcomes.
async function loadDashboardResources() {
const requests = [
fetch('/api/profile').then((response) => response.json()),
fetch('/api/projects').then((response) => response.json()),
fetch('/api/notifications').then((response) => response.json()),
Next.js Route Handler with JSON Validation
Validate a JSON request body and return typed responses from an App Router Route Handler.
// app/api/tasks/route.ts
import { NextResponse } from 'next/server';
type CreateTaskBody = {
title?: unknown;
};
export async function POST(request: Request) {
let body: CreateTaskBody;
try {
body = await request.json();
} catch {
cURL GET Request in PHP
Call an external API with cURL and decode the JSON response.
<?php
$ch = curl_init('https://api.example.com/items');
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 10,
]);
$responseBody = curl_exec($ch);
$statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
PHP Read JSON Request Body
Read and validate a JSON request body in PHP.
<?php
$rawBody = file_get_contents('php://input');
$data = json_decode($rawBody, true);
if (!is_array($data) || json_last_error() !== JSON_ERROR_NONE) {
http_response_code(400);
echo json_encode(['error' => 'Invalid JSON body.']);
exit;
}
PHP JSON Response Helper
Return a JSON response from a small PHP endpoint.
<?php
function json_response(array $payload, int $status = 200): void
{
http_response_code($status);
header('Content-Type: application/json; charset=utf-8');
echo json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
exit;
}
Fetch POST JSON Request
Send JSON data to a backend endpoint with fetch.
async function createNote(note) {
const response = await fetch('/api/notes', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(note)
});
if (!response.ok) {
Fetch GET Request
Load JSON from an API endpoint with async and await.
async function searchSnippets(query) {
const url = `/api/snippets?search=${encodeURIComponent(query)}`;
const response = await fetch(url);
if (!response.ok) {
throw new Error('Search request failed.');
}
Fetch JSON with Error Handling
Fetch JSON data and handle HTTP errors cleanly.
async function loadProfile() {
const response = await fetch('/api/profile');
if (!response.ok) {
throw new Error(`Request failed: ${response.status}`);
}
return await response.json();
}
loadProfile()
Safe JSON Load
Load JSON data from a file and handle invalid JSON safely.
import json
from pathlib import Path
file_path = Path("settings.json")
try:
data = json.loads(file_path.read_text(encoding="utf-8"))
print(data)
except FileNotFoundError:
print("settings.json was not found")
except json.JSONDecodeError:
Simple CSV Reader
Read a CSV file with headers and print selected columns.
import csv
with open("students.csv", newline="", encoding="utf-8") as file:
reader = csv.DictReader(file)
for row in reader:
name = row.get("name", "")
grade = row.get("grade", "")
print(f"{name}: {grade}")
Count Word Frequency
Count how often each word appears in a short text.
text = "python is fun and python is useful"
words = text.lower().split()
counts = {}
for word in words:
counts[word] = counts.get(word, 0) + 1
for word, count in counts.items():
print(word, count)
Filter Even Numbers
Filter even numbers from a list using a simple list comprehension.
numbers = [3, 8, 12, 15, 20, 21, 30]
even_numbers = [number for number in numbers if number % 2 == 0]
print(even_numbers)
Read Text File Lines
Read a text file line by line and remove the newline characters.
from pathlib import Path
file_path = Path("notes.txt")
if not file_path.exists():
print("File not found")
else:
lines = file_path.read_text(encoding="utf-8").splitlines()
for line_number, line in enumerate(lines, start=1):
Save and Load JSON from localStorage
A safe small helper for storing JSON data in localStorage.
function saveJson(key, value) {
localStorage.setItem(key, JSON.stringify(value));
}
function loadJson(key, fallback = null) {
try {
const raw = localStorage.getItem(key);
return raw ? JSON.parse(raw) : fallback;
} catch (error) {