Skip to content

Instantly share code, notes, and snippets.

@helabenkhalfallah
Created April 28, 2024 19:07
Show Gist options
  • Select an option

  • Save helabenkhalfallah/191470042cd68bb8d327fed3aeb4e7fe to your computer and use it in GitHub Desktop.

Select an option

Save helabenkhalfallah/191470042cd68bb8d327fed3aeb4e7fe to your computer and use it in GitHub Desktop.
Solid Fetching Data
import { createResource, For, Match, Switch, Show } from "solid-js";
import { render } from "solid-js/web";
// Define an asynchronous function to fetch user data from an API endpoint
const fetchUser = async () => {
// Fetch user data from the API
const response = await fetch(`https://dummyjson.com/users`);
// Parse the JSON response
const jsonResponse = await response.json();
// Return the array of users from the JSON response
return jsonResponse.users;
};
// Usage in a component
const MyComponent = () => {
// Use createResource to define a resource that represents the user data endpoint
// Pass the fetchUser function to createResource to fetch data asynchronously
const [user] = createResource(fetchUser);
return (
<div>
<h1>User Data</h1>
{/* Show a loading message while data is being fetched */}
<Show when={user.loading}>
<p>Loading...</p>
</Show>
{/* Use a Switch to conditionally render content based on the state of the resource */}
<Switch>
{/* Use Match to handle different states of the resource */}
{/* If an error occurs during fetching, display an error message */}
<Match when={user.error}>
<span>Error: {error()}</span>
</Match>
{/* If data is successfully fetched, iterate over the array of users and render them */}
<Match when={user()}>
{/* Use For to iterate over the array of users */}
{/* For each user, render a list item with their first name */}
<For each={user()}>{(user) => <li>{user.firstName}</li>}</For>
</Match>
</Switch>
</div>
);
};
// Render the MyComponent to the DOM
// Mount it to the element with id "app"
render(() => <MyComponent />, document.getElementById("app")!);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment