question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Hook for initialization?

See original GitHub issue

Is your feature request related to a problem? Please describe. It should be pretty common for a svelt kit app to utilize external services that you need to initialize clients to talk to them. The doc demonstrates such use case:

import db from '$lib/database';

export async function get({ params }) {
	const { slug } = params;
	const article = await db.get(slug);
	// ...
}

One issue with this code is that it assumes db can be initialized in the module itself either synchronously (which is not always the case) or via top-level await (which svelte kit doesn’t seem to support).

Describe the solution you’d like Offer a hook like async func init() {} that only runs once when it starts?

Describe alternatives you’ve considered

How important is this feature to you? Very, since it’s pretty awkward to workaround when the initialization is async (e.g., force initialization to be synchronous and only call the async part when actually talk to external services).

Additional context

Issue Analytics

  • State:closed
  • Created 2 years ago
  • Reactions:14
  • Comments:25 (21 by maintainers)

github_iconTop GitHub Comments

6reactions
rmunncommented, Dec 2, 2021

it initializes my urql client two times!

Is there a workaround today?

Here’s an approach I just thought of.

Create a store in a separate module, say urqlclient.ts. It would look like this:

// urqlclient.ts
import { initClient } from 'svelte-urql';

const noop = () => {};

let client = null;
export const urqlclient = readable(null, (set) => {
  if (!client) {
    client = initClient('whatever params you need');
  }
  set(client);
  return noop;
});

Then when you need an URQL client, get it from the store via $urqlclient. The first time any piece of your code subscribes to this store, the readable’s initialization function will be called. Since it calls set before returning, the first subscriber will receive a non-null value. If that first subscriber unsubscribes before a second subscriber asks for a client, the initialization function will be called again, but the second time it will simply return the cached value of client and not call initClient a second time.

This will allow the rest of your code to just do import { urqlclient } from '$lib/urqlclient.ts' and then use $urqlclient knowing that that value will be a properly-configured client.

5reactions
Rich-Harriscommented, Dec 28, 2021

Top-level await was broken in Vite at the time of https://github.com/sveltejs/kit/issues/1538#issue-899375025, but is since fixed, which means this problem is very easily solved — you can do your setup work in hooks.js

const db = await createConnection();

export function handle({ request, resolve }) {
  request.locals.db = db;
  return resolve(request);
}

…or if that feels weird you can do it in a module that’s imported by any endpoints that need it:

// src/lib/db.js
export const db = await createConnection();
// src/routes/my-endpoint.js
import { db } from '$lib/db';

export async function get() {
  return {
    body: await db.get(...)
  }
}

The latter technique also applies to clients that are needed by pages, like Urql. Demo here.

Given all this, is a dedicated initialization hook necessary?

Read more comments on GitHub >

github_iconTop Results From Across the Web

Simplifying state initializers with React Hooks - LogRocket Blog
Generally speaking, to initialize means to set the value of something. Going by this definition, the state initializer pattern exists to make it ......
Read more >
Hooks API Reference - React
This page describes the APIs for the built-in Hooks in React. If you're new to Hooks, ... There are two different ways to...
Read more >
ReactJS useState Hook - lazy initialization and previous state
ReactJS useState hook is a great way to manage the state of the functional components. Let's learn a couple of interesting usages about...
Read more >
What is the State Initialization Pattern? - Advanced React ...
The state initializer pattern exists to make it easy for the consumer of your custom hook to set the “value of state”. Note...
Read more >
.initialize() - Sails.js
The initialize feature allows a hook to perform startup tasks that may be asynchronous or rely on other hooks. All Sails configuration is...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found