Explore

Explore snippets

Discover reusable code snippets, examples, fixes, and ideas shared by developers, students, and teams.

Public snippets by CodShot user
Clear
17 public snippets
Open
JavaScript
Public

Infinite Scroll with IntersectionObserver

Load the next page when a sentinel approaches the viewport and prevent duplicate requests.

JavaScript Preview
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];
#javascript #intersection-observer #infinite-scroll #performance
CodShot user
CodShot user
Updated: 2026-08-06 18:36
Public snippets
0 #237
Open
TypeScript
Public

Typed JSON Fetch Helper

Wrap fetch with JSON parsing, typed responses, and useful HTTP error messages.

TypeScript Preview
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',
#typescript #fetch #api #json
CodShot user
CodShot user
Updated: 2026-08-06 18:36
Public snippets
0 #235
Open
TypeScript
Public

Async Generator for Paginated API Data

Iterate through paginated API responses without loading every page into memory.

TypeScript Preview
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 {
#typescript #async #pagination #api
CodShot user
CodShot user
Updated: 2026-08-06 18:36
Public snippets
0 #234
Open
JavaScript
Public

Process Mixed Results with Promise.allSettled

Run independent asynchronous tasks and keep both successful and failed outcomes.

JavaScript Preview
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()),
#javascript #promise #async #error-handling
CodShot user
CodShot user
Updated: 2026-08-06 18:36
Public snippets
0 #233
Open
TypeScript
Public

Next.js Route Handler with JSON Validation

Validate a JSON request body and return typed responses from an App Router Route Handler.

TypeScript Preview
// 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 {
#nextjs #route-handler #api #typescript
CodShot user
CodShot user
Updated: 2026-08-06 18:36
Public snippets
0 #226
Open
PHP
Public

cURL GET Request in PHP

Call an external API with cURL and decode the JSON response.

PHP Preview
<?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 #curl #api #json
CodShot user
CodShot user
Updated: 2026-06-08 14:33
Public snippets
0 #128
Open
PHP
Public

PHP Read JSON Request Body

Read and validate a JSON request body in PHP.

PHP Preview
<?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 #api #json #validation
CodShot user
CodShot user
Updated: 2026-06-08 14:33
Public snippets
0 #127
Open
PHP
Public

PHP JSON Response Helper

Return a JSON response from a small PHP endpoint.

PHP Preview
<?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;
}
#php #api #json #response
CodShot user
CodShot user
Updated: 2026-06-08 14:33
Public snippets
0 #126
Open
JavaScript
Public

Fetch POST JSON Request

Send JSON data to a backend endpoint with fetch.

JavaScript Preview
async function createNote(note) {
    const response = await fetch('/api/notes', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(note)
    });

    if (!response.ok) {
#api #javascript #post #json
CodShot user
CodShot user
Updated: 2026-06-08 14:33
Public snippets
0 #125
Open
JavaScript
Public

Fetch GET Request

Load JSON from an API endpoint with async and await.

JavaScript Preview
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.');
    }
#api #javascript #fetch #json
CodShot user
CodShot user
Updated: 2026-06-08 14:33
Public snippets
0 #124
Open
JavaScript
Public

Fetch JSON with Error Handling

Fetch JSON data and handle HTTP errors cleanly.

JavaScript Preview
async function loadProfile() {
    const response = await fetch('/api/profile');

    if (!response.ok) {
        throw new Error(`Request failed: ${response.status}`);
    }

    return await response.json();
}

loadProfile()
#javascript #fetch #json #error-handling
CodShot user
CodShot user
Updated: 2026-06-08 14:33
Public snippets
0 #117
Open
Python
Public

Safe JSON Load

Load JSON data from a file and handle invalid JSON safely.

Python Preview
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:
#python #json #file #error-handling
CodShot user
CodShot user
Updated: 2026-06-03 15:31
Public snippets
0 #83
Open
Python
Public

Simple CSV Reader

Read a CSV file with headers and print selected columns.

Python Preview
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}")
#python #csv #file #student
CodShot user
CodShot user
Updated: 2026-06-03 15:31
Public snippets
0 #82
Open
Python
Public

Count Word Frequency

Count how often each word appears in a short text.

Python Preview
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)
#python #string #dictionary #beginner
CodShot user
CodShot user
Updated: 2026-06-03 15:31
Public snippets
0 #81
Open
Python
Public

Filter Even Numbers

Filter even numbers from a list using a simple list comprehension.

Python Preview
numbers = [3, 8, 12, 15, 20, 21, 30]

even_numbers = [number for number in numbers if number % 2 == 0]

print(even_numbers)
#python #list #beginner #filter
CodShot user
CodShot user
Updated: 2026-06-03 15:31
Public snippets
0 #80
Open
Python
Public

Read Text File Lines

Read a text file line by line and remove the newline characters.

Python Preview
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):
#python #file #beginner #text
CodShot user
CodShot user
Updated: 2026-06-03 15:31
Public snippets
0 #79
Open
JavaScript
Public

Save and Load JSON from localStorage

A safe small helper for storing JSON data in localStorage.

JavaScript Preview
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) {
#javascript #localstorage #json #utility
CodShot user
CodShot user
Updated: 2026-06-03 14:05
Public snippets
0 #66
CodShot AI Help
Ask about CodShot features, plans, workspace, AI limits, referrals, and public help topics.
Hi! I can help you understand how CodShot works. What would you like to know?
For account-specific or sensitive issues, please open a support ticket. Open support