Val Town Code SearchReturn to Val Town

API Access

You can access search results via JSON API by adding format=json to your query:

https://codesearch.val.run/?q=fetch&page=112&format=json

For typeahead suggestions, use the /typeahead endpoint:

https://codesearch.val.run/typeahead?q=fetch

Returns an array of strings in format "username" or "username/projectName"

Found 8568 results for "fetch"(1270ms)

promptmain.tsx3 matches

@salon•Updated 2 weeks ago
1import { fetch } from "https://esm.town/v/std/fetch";
2import { OpenAI } from "https://esm.town/v/std/openai"; // Assuming OpenAI library is available
3import { z } from "npm:zod"; // Using Zod for input validation
173
174 try {
175 const response = await fetch('/generate', {
176 method: 'POST',
177 headers: { 'Content-Type': 'application/json' },
287
288 try {
289 const response = await fetch('/test', {
290 method: 'POST',
291 headers: { 'Content-Type': 'application/json' },

medmain.tsx3 matches

@salon•Updated 2 weeks ago
1import { fetch } from "https://esm.town/v/std/fetch";
2import { OpenAI } from "https://esm.town/v/std/openai";
3import { z } from "npm:zod";
87 const setupInForQ = (q) => { clrInArea(); currentQ = q; let inp; const commonEnter = (ev) => { if (ev.key === 'Enter' && !ev.shiftKey) { ev.preventDefault(); sendHandler(); } }; switch (q.type) { case 'select': inp = document.createElement('select'); inp.id = 'user-input'; inp.className = 'form-control'; (q.opts || []).forEach(opt => { const o = document.createElement('option'); o.value = opt.value; o.textContent = opt.label; inp.appendChild(o); }); break; case 'textarea': inp = document.createElement('textarea'); inp.id = 'user-input'; inp.rows = 3; inp.placeholder = "Enter details..."; inp.className = 'form-control'; inp.addEventListener('keypress', commonEnter); break; case 'number': inp = document.createElement('input'); inp.type = 'number'; inp.id = 'user-input'; inp.placeholder = "Enter number..."; if (q.min != null) inp.min = q.min; if (q.max != null) inp.max = q.max; inp.className = 'form-control'; inp.addEventListener('keypress', commonEnter); break; default: inp = document.createElement('input'); inp.type = 'text'; inp.id = 'user-input'; inp.placeholder = "Your answer..."; inp.className = 'form-control'; inp.addEventListener('keypress', commonEnter); break; } const btn = document.createElement('button'); btn.id = 'send-button'; btn.textContent = 'Send'; btn.onclick = sendHandler; inputArea.append(inp, btn); enableInput(true); inp.focus(); };
88 const sendHandler = async () => { const inp = document.getElementById('user-input'); if (!inp || !currentQ) return; let answer = inp.value; if (currentQ.type === 'number') { const num = parseFloat(answer); answer = !isNaN(num) ? num : (answer.trim() === '' ? '' : answer); } clrErr(); let displayAnswer = typeof answer === 'number' ? answer.toString() : answer; if (currentQ.type === 'select') { const opt = Array.from(inp.options).find(o => o.value === answer); displayAnswer = opt ? opt.text : answer; if (answer === "") displayAnswer = "(Skipped)"; } else if (typeof answer === 'string' && !answer.trim() && currentQ.type !== 'textarea') { displayAnswer = "(No input)"; } if (displayAnswer && !["(Skipped)", "(No input)"].includes(displayAnswer)) addUser(displayAnswer); else if (typeof answer === 'string' && !answer.trim() && currentQ.type === 'textarea') addUser("(Empty details)"); const lastAns = { field: currentQ.fld, value: answer }; clrInArea(); enableInput(false); setLoad(true); await sendToSrv({ task: task, sessionId: sid, lastAnswer: lastAns, state: srvState }); };
89 const sendToSrv = async (pld) => { try { console.log("-> /questionnaire:", pld); const resp = await fetch('/questionnaire', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(pld) }); setLoad(false); clrErr(); if (!resp.ok) { let msg = \`Server error: \${resp.status} \${resp.statusText}\`; try { msg += \` - \${(await resp.json()).error || 'Details unavailable'}\` } catch(e){} throw new Error(msg); } const data = await resp.json(); console.log("<- /questionnaire:", data); sid = data.sid; srvState = data.state; if (data.error) { showErr(data.error); if (currentQ) { addBot(\`Issue: \${data.error}. Try again.\`); setupInForQ(currentQ); } else { addBot(\`Error: \${data.error}. Select task again.\`); showTasks(); } return; } if (data.isDone) { addBot("Info gathered. Processing..."); enableInput(false); clrInArea(); setLoad(true); await execWf(data.data); } else if (data.nextQ) { addBot(data.nextQ.txt); setupInForQ(data.nextQ); } else { showErr("Unexpected server response."); enableInput(false); addBot("Something went wrong. Refresh and try again."); } } catch (err) { console.error("Comm error:", err); setLoad(false); showErr(\`Comm error: \${err.message}\`); enableInput(false); addBot("Connection issue. Refresh to start over."); } };
90 const execWf = async (finalPld) => { enableInput(false); try { console.log("-> /execute:", finalPld); if (!finalPld?.task || !finalPld.data) throw new Error("Invalid execution payload."); const resp = await fetch('/execute', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(finalPld) }); setLoad(false); const resData = await resp.json(); console.log("<- /execute:", resData); resDisp.style.display = 'block'; setTimeout(() => resDisp.classList.add('visible'), 10); resCont.innerHTML = ''; logCont.innerHTML = ''; if (!resp.ok || resData.error) { const msg = resData.error || \`Exec failed: Status \${resp.status}\`; resCont.innerHTML = \`<div class="error-message">\${esc(msg)}</div>\`; if(resData.dtls) resCont.innerHTML += \`<p>Details: \${esc(typeof resData.dtls === 'string' ? resData.dtls : JSON.stringify(resData.dtls))}</p>\`; addBot(\`Error processing request: \${esc(msg)}\`); } else { resCont.innerHTML = fmtRes(resData.result, finalPld.task); addBot("Request complete! See results."); } logCont.innerHTML = fmtLogs(resData.logs); clrInArea(); showTasks(); } catch (err) { console.error("Exec error:", err); setLoad(false); resDisp.style.display = 'block'; setTimeout(() => resDisp.classList.add('visible'), 10); resCont.innerHTML = \`<div class="error-message">Execution failed: \${esc(err.message)}</div>\`; logCont.innerHTML = fmtLogs(null); addBot("Critical error during execution. Check logs or retry."); clrInArea(); showTasks(); } };
91 const fmtList = (items, tag='li') => items && items.length > 0 ? \`<ul>\${items.map(i => \`<$\{tag\}>\${esc(i)}</\$\{tag\}>\`).join('')}</ul>\` : '';
92 const fmtDictList = (items) => items && items.length > 0 ? \`<ul>\${items.map(d => \`<li><strong>\${esc(d.dx || d.diagnosis)}</strong>\${(d.rationale) ? \`: \${esc(d.rationale)}\` : ''}</li>\`).join('')}</ul>\` : '';

pondiversefetchCreations0 matches

@elouan•Updated 2 weeks ago
1import { blob } from "https://esm.town/v/std/blob";
2import { sqlite } from "https://esm.town/v/stevekrouse/sqlite";
3import { TABLE_NAME } from "./updateTable";
4
5export default async function(req: Request): Promise<Response> {

svcmain.tsx15 matches

@salon•Updated 2 weeks ago
41 const [strategyError, setStrategyError] = useState<string | null>(null);
42
43 // --- Fetch Profile ---
44 const fetchProfile = useCallback(async () => {
45 setIsLoadingProfile(true);
46 setProfileError(null);
47 try {
48 const response = await fetch("/api/profile");
49 if (response.status === 404) {
50 setProfile(null);
59 } else if (!response.ok) {
60 const data = await response.json();
61 throw new Error(data.error || "Failed to fetch profile");
62 } else {
63 const data = await response.json();
64 setProfile(data);
65 setFormData({ // Pre-fill form with fetched data or defaults
66 business_type: data.business_type || "",
67 service_area: data.service_area || "",
74 } catch (err: any) {
75 setProfileError(err.message);
76 console.error("Fetch profile error:", err);
77 } finally {
78 setIsLoadingProfile(false);
81
82 useEffect(() => {
83 fetchProfile();
84 }, [fetchProfile]);
85
86 // --- Input Handlers ---
98 setStrategyError(null);
99 try {
100 const response = await fetch("/api/profile", {
101 method: "POST",
102 headers: { "Content-Type": "application/json" },
127 setStrategy(null);
128 try {
129 // Use POST to trigger generation, profile is fetched server-side
130 const response = await fetch("/api/generate-strategy", { method: "POST" });
131 const data = await response.json();
132 if (!response.ok) {
441 } catch (e: any) {
442 /* ... error handling ... */
443 console.error("Error fetching profile:", e.message);
444 return new Response(JSON.stringify({ error: "Database error fetching profile" }), {
445 status: 500,
446 headers: { "Content-Type": "application/json" },
477 if (url.pathname === "/api/generate-strategy" && request.method === "POST") {
478 let profile: any = null;
479 // 1. Fetch the enhanced profile
480 try {
481 const { rows } = await sqlite.execute({
495 }
496 } catch (e: any) {
497 /* ... error handling ... */ return new Response(JSON.stringify({ error: "DB error fetching profile" }), {
498 status: 500,
499 });

business_finder_productionmain.tsx1 match

@run•Updated 2 weeks ago
955
956 // Simulação de geocodificação reversa
957 fetch(\`https://nominatim.openstreetmap.org/reverse?format=json&lat=\${lat}&lon=\${lng}&accept-language=pt-BR\`)
958 .then(response => response.json())
959 .then(data => {

avidAzureKiwimain.tsx3 matches

@tallesjp•Updated 2 weeks ago
4
5 try {
6 const initialResponse = await fetch(baseUrl);
7 const initialHtml = await initialResponse.text();
8
23 links.map(async (pageUrl) => {
24 try {
25 const response = await fetch(pageUrl);
26 const html = await response.text();
27 const content = extractPureContent(html);
28 return content ? `## ${pageUrl}\n\n${content}` : '';
29 } catch (error) {
30 console.error(`Failed to fetch ${pageUrl}:`, error);
31 return '';
32 }

mohitkingsprojectmain.tsx17 matches

@Mkv•Updated 2 weeks ago
88 ];
89
90 // Fetch currency rates
91 useEffect(() => {
92 async function fetchCurrencyRates() {
93 try {
94 const response = await fetch("https://open.exchangerate-api.com/v6/latest");
95 const data = await response.json();
96 setCurrencyRates(data.rates);
97 } catch (error) {
98 console.error("Failed to fetch currency rates:", error);
99 }
100 }
101 fetchCurrencyRates();
102 }, []);
103
104 // Cryptocurrency data fetching
105 useEffect(() => {
106 async function fetchCoinData() {
107 try {
108 setLoading(true);
109 const response = await fetch(
110 "https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&order=market_cap_desc&per_page=10&page=1&sparkline=false",
111 );
114 setLoading(false);
115 } catch (error) {
116 console.error("Failed to fetch coin data:", error);
117 setLoading(false);
118 }
119 }
120
121 fetchCoinData();
122
123 const refreshInterval = autoRefresh
124 ? setInterval(() => {
125 fetchCoinData();
126 setRefreshCount(prev => prev + 1);
127 }, 60000)
148 );
149
150 // Price history fetching
151 const fetchPriceHistory = async (coinId: string, days: string) => {
152 try {
153 const response = await fetch(
154 `https://api.coingecko.com/api/v3/coins/${coinId}/market_chart?vs_currency=usd&days=${days}`,
155 );
166 setChartError(null);
167 } catch (error) {
168 console.error(`Failed to fetch ${days} price history:`, error);
169 setChartError(`Unable to load ${days} price history`);
170 }
279 onClick={() => {
280 setSelectedCoin(coin);
281 fetchPriceHistory(coin.id, "24h");
282 }}
283 className={`p-4 rounded-lg cursor-pointer ${
313 <button
314 key={range}
315 onClick={() => fetchPriceHistory(selectedCoin.id, range)}
316 className={`p-2 rounded ${
317 selectedTimeRange === range

valProfilePageREADME.md1 match

@dcm31•Updated 2 weeks ago
64- Hono (server-side)
65- Tailwind CSS (styling)
66- Uses the Charlie's User Search API for fetching user val data
67- Uses Val Town's profile picture proxy for user avatars
68

valProfilePageindex.ts7 matches

@dcm31•Updated 2 weeks ago
4const app = new Hono();
5
6// API endpoint to fetch user profile data
7app.get("/api/profile/:username", async (c) => {
8 const username = c.req.param("username");
10 try {
11 // Call the user search API
12 const response = await fetch(
13 `https://charliesusersearch.val.run/?user=${username}`
14 );
15
16 if (!response.ok) {
17 return c.json({ error: "Failed to fetch user data" }, 500);
18 }
19
21 return c.json(data);
22 } catch (error) {
23 console.error("Error fetching user data:", error);
24 return c.json({ error: "Failed to fetch user data" }, 500);
25 }
26});
52});
53
54// HTTP vals expect an exported "fetch handler"
55// This is how you "run the server" in Val Town with Hono
56export default app.fetch;

valProfilePageValGridItem.tsx7 matches

@dcm31•Updated 2 weeks ago
1/** @jsxImportSource https://esm.sh/react@18.2.0 */
2import React, { useState, useEffect } from "https://esm.sh/react@18.2.0";
3import { fetchMoiConfig } from "../utils/moiConfig.tsx";
4
5interface Val {
45 };
46
47 // Attempt to fetch moi.md for this val if it doesn't have an image
48 useEffect(() => {
49 const fetchMoiData = async () => {
50 // Only try to fetch moi.md if there's no image_url
51 if (!val.image_url) {
52 try {
59 // Construct the base URL for the val/project
60 const baseUrl = urlParts.slice(0, xIndex + 3).join('/');
61 const config = await fetchMoiConfig(baseUrl);
62 setMoiConfig(config);
63 }
64 } catch (error) {
65 console.error("Error fetching moi.md for val:", error);
66 }
67 }
68 };
69
70 fetchMoiData();
71 }, [val.url, val.image_url]);
72

fetchPaginatedData2 file matches

@nbbaier•Updated 2 weeks ago

FetchBasic1 file match

@fredmoon•Updated 2 weeks ago