Appending Multiple Parameters

Avatar of Hemanta SundarayHemanta Sundaray

To append several parameters with the same key, use HttpClientRequest.appendUrlParams():

http.ts
import {
FetchHttpClient,
HttpClient,
HttpClientRequest,
} from "effect/unstable/http";
import { Effect } from "effect";
function fetchPosts(tags: string[]) {
return Effect.gen(function* () {
const client = yield* HttpClient.HttpClient;
// Convert array to tuples for duplicate keys
const tagTuples: Array<[string, string]> = tags.map((tag) => ["tag", tag]);
const request = HttpClientRequest.get("https://dummyjson.com/posts").pipe(
HttpClientRequest.setUrlParam("limit", "3"),
HttpClientRequest.appendUrlParams(tagTuples),
);
console.log("URL Params:", request.urlParams);
const response = yield* client.execute(request);
const data = yield* response.json;
return data;
}).pipe(Effect.provide(FetchHttpClient.layer));
}
// Test it
Effect.runPromise(fetchPosts(["love", "history", "mystery"])).then((data) => {
data.posts.forEach((post: any) => {
console.log(` - "${post.title.slice(0, 40)}..."`);
console.log(` Tags: ${post.tags.join(", ")}`);
});
});

Output:

Terminal
URL Params: [
[ 'limit', '3' ],
[ 'tag', 'love' ],
[ 'tag', 'history' ],
[ 'tag', 'mystery' ]
]
- "His mother had always taught him..."
Tags: history, american, crime
- "He was an expert but not in a discipline..."
Tags: french, fiction, english
- "Dave watched as the forest burned up on ..."
Tags: magical, history, french

Notice the tagTuples conversion in the example above.

appendUrlParams() expects an array of [key, value] tuples, not an object. This is what makes duplicate keys possible.

An object like { tag: "love", tag: "history" } would silently overwrite earlier values, leaving you with only the last one. Tuples don’t have this limitation, so tags.map((tag) => ["tag", tag]) produces [["tag", "love"], ["tag", "history"], ["tag", "mystery"]], giving each tag its own entry in the query string.

Sign in to save progress

Stay in the loop

Get notified when new Effect Atom related content is published.