Resources
Fetch and manage async data with createResource
.
createResource
is a feature in Olova that allows you to fetch and manage asynchronous data efficiently. It simplifies the process of handling data fetching and ensures that your UI stays in sync with the data state.
Here's a practical example using createResource
:
jsx
import { createResource } from "olova";
const fetchUser = async (id) => {
const response = await fetch(`https://api.example.com/users/${id}`);
return response.json();
};
function UserProfile({ userId }) {
const [user] = createResource(userId, fetchUser);
return (
<div>
{user.loading && <p>Loading...</p>}
{user.error && <p>Error loading user data.</p>}
{user() && (
<div>
<h1>{user().name}</h1>
<p>Email: {user().email}</p>
</div>
)}
</div>
);
}
export default UserProfile;
Explanation
- Creating a Resource: We use
createResource(userId, fetchUser)
to fetch user data asynchronously. ThecreateResource
function takes a parameter and a fetch function, managing the loading, error, and data states. - Handling States: The component checks
user.loading
anduser.error
to display appropriate messages while the data is being fetched or if an error occurs. - Rendering the UI: Once the data is fetched, the component displays the user's name and email.
This example demonstrates how createResource
can be used to efficiently fetch and manage asynchronous data in Olova, ensuring that your application can handle data fetching smoothly and reactively.
jsx
const fetchUser = async (id) => {
const response = await fetch(`https://api.example.com/users/${id}`);
return response.json();
};
const [user] = createResource(1, fetchUser);