@mwap

Data Loaders

MWAP introduces the concept of Data Loaders to help you reason about your data and access it from any level of your component tree.

Even though you could useLoader in any component, we recommend reserving it for components defined in your pages directory and keeping them 1:1.

Data Loaders are defined as an object with a loader property.

loaders/home.ts:

import type { Loader } from "mwap";
export type HomePageData = {
name: string;
};
const loader: Loader<HomePageData> = () => {
return {
name: "World",
};
};
export default { loader };

They are then exported from loaders/index.ts, loaders/index.tsx, loaders/index.js or loaders/index.jsx via the name you wish to reference them as in useLoader.

loaders/index.ts:

import home from "./home";
export default {
home,
};

Now we can consume the result of the loader via the useLoader hook.

pages/home.ts:

import * as React from "react";
import { useLoader } from "mwap";
import type { HomePageData } from "../loaders/home";
const HomePage = () => {
const { name } = useLoader<HomePageData>("home");
return <h1>Hello, {name}!</h1>;
};
export default HomePage;

Passing Params

Parameters as passed to the loader through the useLoader hook. These are of course optional, but are useful for contextual loading such as a slug in the Path.

loaders/todo.ts:

import { fetch } from "cross-fetch";
import type { Loader } from "mwap";
export type TodoPageData = {
userId: number;
id: number;
title: string;
completed: boolean;
};
export type TodoPageArgs = {
id: string | number;
};
const loader: Loader<TodoPageData, TodoPageArgs> = async ({ params }) => {
return fetch(
`https://jsonplaceholder.typicode.com/todos/${params.id}`
).then((response) => response.json());
};
export default { loader };

pages/todo.tsx:

import * as React from "react";
import { useParams } from "react-router-dom";
import { useLoader } from "mwap";
import type { TodoPageData, TodoPageArgs } from "../loaders/todo";
const TodoPage = () => {
const { id } = useParams<TodoPageArgs>();
const todo = useLoader<TodoPageData, TodoPageArgs>("todo", { id });
return (
<pre>
<code>{JSON.stringify(todo, null, 2)}</code>
</pre>
);
};
export default TodoPage;

pages/index.ts:

import type { Page } from "mwap";
import Home from "./home";
import Todo from "./todo";
const pages: Page[] = [
{
component: Home,
exact: true,
path: "/",
},
{
component: Todo,
path: "/todo/:id",
},
];
export default pages;

Related

For more information on what to do next, we recommend the following sections: