Reference · Browser

receive

signature
receive(str, fn, map | null=) -> null | error(str)

What it does

In an event handler of a component, sends a request and calls f with what the answer streams, piece by piece, until it ends: each event's data (parsed as JSON when it is JSON, with the event's name as a second parameter when f declares one), each line of newline-delimited JSON, or each piece of text. The options are method, body and headers. It gives null once the stream has ended, or an error value when the answer could not be had. The handler waits for it.

Examples

in a program
route POST /ask = events((send) => http.stream("https://api.example.com/v1/chat", send, {    body: { prompt: request.json.prompt, stream: true },    headers: { authorization: `Bearer ${env("API_KEY")}` },}))component Chat() {    state prompt = ""    state answer = ""    state problem = null    <div>        <input value={prompt}/>        <button @click={() => {            answer = ""            let r = receive("/ask", (part) => { answer = answer + part.text }, { body: { prompt } })            problem = is_err(r) ? r.error : null        }}>Ask</button>        <p>{answer}</p>        {problem && <p class="error">{problem}</p>}    </div>}

Edge cases

print(receive("/ask", (part) => part, { body: { prompt: "hi" } }))
output
null

Errors

A URL that is not a string, or a second argument that is not a function, is a runtime error, not an error value, on the server as in the browser. A request that fails is an error value, checked with is_err or given a default with ??.

this one fails
print(receive(42, (part) => part))
output
line 1: `receive` takes a URL and a function: receive("/reply", (t) => { text = text + t })

Chaining

The result is checked after the stream, as a server fn call's is:

in a program
@click={() => {    let r = receive("/export", (line) => { rows = rows + [line] })    if is_err(r) { notify("Export failed", { tone: "danger" }) }}}

See also

listen, events, stream, http.stream, http.post

Thread
7Useful? Like it, or add to its thread below.

Thread 0 posts

On receive(): questions, tips, corrections, and code that uses it.

No posts yet. The first one opens the thread.

    Edit this page on GitHub · every example's output was made by running it (tools/refcheck.mjs) · questions on Discord or r/quillo