mirror of
https://github.com/lainbo/component-party.git
synced 2026-04-05 13:09:03 +08:00
Rewrite Mithril "Fetch Data" example (#210)
* Rewrite Mithril "Fetch Data" example * Delete obsolete useFetchUsers.js * Conform to existing examples
This commit is contained in:
@@ -1,30 +1,36 @@
|
||||
import m from "mithril";
|
||||
import { fetchUsers } from "./useFetchUsers";
|
||||
|
||||
export default function App() {
|
||||
let isLoading = false;
|
||||
let error = null;
|
||||
let users = [];
|
||||
|
||||
const onSuccess = (data) => (users = data);
|
||||
const onError = (err) => (error = err);
|
||||
fetchUsers(isLoading, onSuccess, onError);
|
||||
async function fetchUsers() {
|
||||
isLoading = true;
|
||||
try {
|
||||
const { results } = await m.request(
|
||||
"https://randomuser.me/api/?results=3"
|
||||
);
|
||||
users = results;
|
||||
} catch (err) {
|
||||
error = err;
|
||||
}
|
||||
isLoading = false;
|
||||
}
|
||||
|
||||
return {
|
||||
view: () =>
|
||||
m(
|
||||
"",
|
||||
isLoading && m("p", "Fetching users..."),
|
||||
error
|
||||
? m("p", "An error occurred while fetching users")
|
||||
: users.map((user) =>
|
||||
m(
|
||||
"li",
|
||||
{ key: user.login.uuid },
|
||||
m("img", { src: user.picture.profile, alt: "user" }),
|
||||
m("p", `${user.name.first} ${user.name.last}`)
|
||||
)
|
||||
)
|
||||
),
|
||||
oninit: fetchUsers,
|
||||
view() {
|
||||
if (isLoading) return m("p", "Fetching users...");
|
||||
if (error) return m("p", "An error occurred while fetching users");
|
||||
return users.map((user) =>
|
||||
m(
|
||||
"li",
|
||||
{ key: user.login.uuid },
|
||||
m("img", { src: user.picture.thumbnail, alt: "user" }),
|
||||
m("p", `${user.name.first} ${user.name.last}`)
|
||||
)
|
||||
);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,15 +0,0 @@
|
||||
import m from "mithril";
|
||||
|
||||
export const fetchUsers = (isLoading, onSuccess, onError) => {
|
||||
isLoading = true;
|
||||
m.request("https://randomuser.me/api/?results=3").then(
|
||||
(data) => {
|
||||
isLoading = false;
|
||||
onSuccess(data);
|
||||
},
|
||||
(err) => {
|
||||
isLoading = false;
|
||||
onError(err);
|
||||
}
|
||||
);
|
||||
};
|
||||
Reference in New Issue
Block a user