Skip to content

Commit

Permalink
Rewrite Mithril "Fetch Data" example (#210)
Browse files Browse the repository at this point in the history
* Rewrite Mithril "Fetch Data" example

* Delete obsolete useFetchUsers.js

* Conform to existing examples
  • Loading branch information
entibo authored Dec 28, 2023
1 parent 20494fd commit e766539
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 34 deletions.
44 changes: 25 additions & 19 deletions content/7-webapp-features/2-fetch-data/mithril/App.js
Original file line number Diff line number Diff line change
@@ -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}`)
)
);
},
};
}
15 changes: 0 additions & 15 deletions content/7-webapp-features/2-fetch-data/mithril/useFetchUsers.js

This file was deleted.

0 comments on commit e766539

Please sign in to comment.