Last active
April 28, 2024 19:26
-
-
Save helabenkhalfallah/1b60b1a3f81751c20a49f6df414556aa to your computer and use it in GitHub Desktop.
Simple Load More List
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { | |
createSignal, | |
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 (page) => { | |
// Fetch user data from the API | |
const response = await fetch( | |
`https://dummyjson.com/users?limit=${5*page}`, | |
); | |
// 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 = () => { | |
const [currentPage, setCurrentPage] = createSignal(1); | |
// 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(currentPage, fetchUser); | |
const handleLoadMore = () => { | |
setCurrentPage(currentPage() + 1); | |
}; | |
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> | |
<button onClick={handleLoadMore}>Load more</button> | |
</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