Solid Start is having difficulty executing the Create Effect feature

The function getName is successfully retrieving the name of the person with id 1 from the database, but there seems to be an issue as this code is not logging anything to the console, not even the debug console.log("running"):

import { Database } from '~/types';
import { Kysely, PostgresDialect } from 'kysely';
import pkg from 'pg';
import { createEffect, createSignal } from 'solid-js';
const { Pool } = pkg;

const dialect = new PostgresDialect({
  pool: new Pool({
    database: 'db',
    host: 'fakehost',
    user: 'user',
    port: 5432,
    max: 10,
    ssl: true,
    password: 'password123',
    
  }),
});

const db = new Kysely<Database>({
  dialect,
});

async function getName(id: number) {
  const x = await db.selectFrom('person').selectAll().where("id" , "=" , id).execute();
  await console.log(x[0].first_name) //does not execute or show anything
  return x[0].first_name;
}

export default function Myperson() {
  
  //getName(1) runs and log to the console 'Jhon' successfully but
  const [name , setName] = createSignal('Loading...')
  createEffect(() => {
    (async () => {
      console.log("Running") //does not execute or show anything
      const nameResult = await getName(1);
      setName(nameResult);
    })();
  });
  return (
    <div>
      {name()}
    </div>
  );
}

Answer №1

Client-side effects in SolidJS run synchronously, meaning they cannot subscribe to asynchronous values. It is important to note that computations created outside of a createRoot or render block will never be disposed, as indicated by the warning message below:

Computations created outside a createRoot or render will never be disposed

For more information, refer to these resources:

  • SolidJS: "computations created outside a createRoot or render will never be disposed" message
  • Why does Solid.js createEffect not re-run when a signal is in a setTimeout callback?

Answer №2

In the given scenario, the effect will not be triggered.

One way to handle this is by using createResource.

Alternatively, you can try implementing a similar solution on your own to gain a better understanding of async handling.

For instance, separate your async code from the effect like this:

function MyPerson() {
    const [name, setName] = createSignal('Loading...')

    console.log('Executing')

    getName().then(setName)

    createEffect(() => console.log('name:', name()))

    return <h1>{name()}</h1>
}

The effectiveness of the getName function cannot be determined without a live working example.

To receive more precise assistance, provide a live demonstration (e.g., on CodePen, CodeSandbox, StackBlitz, or Solid.js Playground).

Please note: Solid effects operate synchronously and do not track async code. It's crucial to maintain a clear distinction between your async operations and Solid effects.

You can view a sample on Solid.js Playground here.

If the getName function is malfunctioning, it might not be related to Solid. Consider seeking advice on Kysely and Postgres separately.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

XCODE encountered an issue while attempting to open the input file located at '/Users/name/Desktop/test/appname/node_modules/react-native-compressor/ios/Video/Compressor-Bridging-Header.h'

Encountering an issue while running my project in XCode. I recently added the react-native-compressor package by following the steps mentioned in the installation guide When attempting to run the project in XCode, the error below occurs: <unknown> ...

Guide to developing a universal store extension

I've been attempting to create a reactive global $store object using a plugin, but so far I have not been successful in getting it to function as intended. store.ts: import {reactive} from "vue"; export default { install: (app:any, opt ...

Tips for Simplifying Complex Switch Cases with Object Literals in TypeScript

I have a unique situation where I need to switch between two functions within an object literal. One function takes two numerical arguments, "A" and "B", while the other function only takes a single string argument, "C". My TypeScript code showcases my di ...

Encountering build issues after transitioning from Angular version 9.17 to 9.19

After upgrading from Angular 9.17 to 9.19, my ng build process started failing with an error related to variable declaration in both @types/node and zone.js: ERROR in node_modules/@types/node/ts3.5/globals.global.d.ts:1:13 - error TS2403: Subsequent varia ...

What is the process for triggering property decorators during runtime?

Wondering about dynamically invoking a property decorator at runtime. If we take a look at the code snippet below: function PropertyDecorator( target: Object, // The prototype of the class propertyKey: string | symbol // The name of th ...

Is it possible for the button text to switch from Farewell to Greetings after two clicks?

There seems to be a strange issue in my React TS project - I have to click the button twice to switch the text from "Goodbye" to "Hello", but not the other way around. Any ideas why? import { useState } from 'react' const ChangeTextButton = () ...

Manage the recently implemented features with TypeScript in IntelliJ

When using IntelliJ with TypeScript and referencing a new function in an .html file, IntelliJ has the option to automatically add this function to the corresponding .component.ts file. For example: <div *ngIf="ifConditionIsTrue()"> Intell ...

Avoid retrieving information from Firestore

Hey everyone, I'm struggling to figure out why I can't retrieve data from Firestore. Even after carefully reading the documentation and double-checking the path, I still can't seem to make it work. I'm working with Ionic framework. getC ...

Verifying TypeScript Class Instances with Node Module Type Checking

My current task involves converting our Vanilla JS node modules to TypeScript. I have rewritten them as classes, added new functionality, created a legacy wrapper, and set up the corresponding Webpack configuration. However, I am facing an issue with singl ...

How to connect multiple HTTP requests using observables in Angular 7

Is there a more efficient way to remove an alert only if it is not assigned to any user? Currently, I am checking my users list and filtering out the users who have this alert assigned using observables. But I wonder if there is a better approach to achi ...

Methods for handling various return types in Typescript

My code includes a method as shown below: abstract canDeactivate() : boolean | Promise<boolean>; I am seeking advice on how to handle both the promise and boolean implementations of this method in the caller's code. ...

Exploring the insights into React-hook-form Controller

I've inherited a website project that utilizes an unfamiliar method in the Controller part of react-hook-form. Here is an example of the code snippet: const CheckboxController = (props: CheckboxProps) => { return ( <Wrapper> < ...

A guide on implementing radio buttons in Angular 2 and sending the selected value via a HTTP post request

As a newcomer to Angular 2, I am struggling with the following code: Here is my HTML <form action="POST" (submit)="register()" class="aa-login-form"> <input type="radio" [(ngModel)]="gender" name="sex" value="MALE"> Male <input ...

What are some ways to incorporate inline TypeScript Annotations into standard JavaScript code?

If you're using VSCode, there's a new feature that allows you to implement type checking for traditional JavaScript files. There are instances where I wish to specify the type of a variable or parameters in a method or function to enhance auto-co ...

Understanding Typescript typings and npm packages can greatly improve your development workflow

I'm pleased to see that NPM has now included support for importing TypeScript type wrappers. However, I've noticed inconsistency in how these wrappers are maintained. For instance, when attempting to import "node-git" and "@types/node-git", I fou ...

The absence of definition for onSubmit is causing an issue in Angular 6

I am encountering an issue with validating the sign-in form as it is showing an error stating onSubmit is not defined. Below is the code snippet: import { Component, OnInit } from '@angular/core'; import { FormArray, FormControl, FormGroup, Vali ...

Accessing properties in TypeScript using an index that is determined by another property within the same interface

Allow me to illustrate my query with an example rather than simply using words: interface Y { x: number, y: string } interface PairValue<T> { key: keyof T, value: T[this['key']] } const pairValue: PairValue<Y> = { ...

Does Angular 1.3.x have a corresponding .d.ts file available?

Is there a .d.ts file available for Angular 1.3.x to assist in transitioning an app to Typescript 2.0? ...

Using lodash to combine the values of identical objects

As a newcomer to development, I am looking to group similar objects within an array of JSON objects. Here is an example of my JSON array: var data = [ { zone: "Bottom", group: "Bottom girders", original: 7, ...

How to dynamically assign a type based on a single choice from multiple options (props)

I have a props object that includes: { option1, option2, option3, option4, general, otherProps } The requirement is to allow only one option to be used at a time. Here are the types defined: interface MyTypes { option1: boolean option2: boolean option3 ...