For software development and maintenance, contact me at contact@appsoftware.com or via appsoftware.com


SolidJS: how to use async methods in createEffect?

Tue, 28 Mar 2023 by garethbrown

In SolidJS, createEffect is used to run side effects, and it does not support async functions or await directly. However, you can still work with asynchronous tasks inside createEffect by using then or catch on Promises.

You can use then and catch on any function that returns a Promise.

Here's an example of how to handle async methods inside createEffect:

Javascript:


import { createEffect, createSignal } from 'solid-js';

const [data, setData] = createSignal(null);
const [error, setError] = createSignal(null);

createEffect(() => {
  // Fetch data from an API
  fetch('https://api.example.com/data')
    .then((response) => {
      if (!response.ok) {
        throw new Error('Network response was not ok');
      }
      return response.json();
    })
    .then((data) => {
      setData(data);
      setError(null);
    })
    .catch((error) => {
      setError(error.message);
      setData(null);
    });
});

Typescript:

import { createEffect, createSignal, Signal } from 'solid-js';

interface Data {
  // Define your data structure here, e.g.,
  id: number;
  name: string;
}

const [data, setData] = createSignal<Data | null>(null);
const [error, setError] = createSignal<string | null>(null);

createEffect(() => {
  // Fetch data from an API
  fetch('https://api.example.com/data')
    .then((response) => {
      if (!response.ok) {
        throw new Error('Network response was not ok');
      }
      return response.json();
    })
    .then((data: Data) => {
      setData(data);
      setError(null);
    })
    .catch((error: Error) => {
      setError(error.message);
      setData(null);
    });
});

The information provided on this Website is for general informational and educational purposes only. While we strive to provide accurate and up-to-date information, we make no warranties or representations, express or implied, as to the accuracy, completeness, reliability, or suitability of the content, including code samples and product recommendations, presented on this Website.

The use of any information, code samples, or product recommendations on this Website is entirely at your own risk, and we shall not be held liable for any loss or damage, direct or indirect, arising from or in connection with the use of this Website or the information provided herein.
UI block loader
One moment please ...