Rewrite Mithril "Fetch Data" example (#210)

* Rewrite Mithril "Fetch Data" example

* Delete obsolete useFetchUsers.js

* Conform to existing examples
This commit is contained in:
Thibaut Guénédal
2023-12-28 14:23:09 +01:00
committed by GitHub
parent 20494fd06e
commit e766539379
2 changed files with 25 additions and 34 deletions

View File

@@ -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}`)
)
);
},
};
}

View File

@@ -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);
}
);
};