Page props
Page props with AdonisJS and Inertia are a powerful feature that allows you to pass data to your pages.
Passing data to pages
Going into the index_controller.ts
file you'll see that we return an inertia.render
function.
async index({ inertia, request }: HttpContext) {
const payload = await indexValidator.validate(request.all());
let products = await this.productService.getProducts();
return inertia.render("index", {
products: ProductPresenter.presentList(products),
referer: payload.referer
});
}
We are passing the products
and referer
to the index.tsx
file.
The index.tsx
have this in params:
props: InferPageProps<IndexController, 'index'>
, where IndexController
is the controller name and index
is the method name.
const Home = (props: InferPageProps<IndexController, 'index'>) => {
return (
<>
<Seo title={`${AppConfig.brandName} - The ultimate boilerplate for your needs.`}
description={"TurboSaaS is a comprehensive AdonisJS boilerplate with Inertia.js, enabling developers to quickly ship projects with built-in features like Stripe, Lemon Squeezy, and authentication."}
keywords={"TurboSaaS, AdonisJS, Inertia.js, boilerplate, Stripe integration, Lemon Squeezy, authentication, developer tools, SaaS, web development, turbosaas, shipfast, boilerplate, saas, saas boilerplate, saas tool, saas generator, saas template,"} />
<Hero />
<HowItWorks />
<FeaturesSection />
<AutomaticPricing productList={props.products} />
<Testimonials />
</>
);
};
Try it! Do some props. and let the magic happen. Everything is typed, and you'r sure to receive that data. Now, you can use it in your components.
Passing user data to pages
Go into /config/inertia.ts
file, and you'll find the sharedData
property.
sharedData: {
errors: (ctx) => ctx.session?.flashMessages.get("errors"),
user: async (ctx) => {
if (ctx.auth.user) {
await ctx.auth.user.load('address')
return ctx.auth.user
}
return undefined
},
toast: (ctx) => ctx.session?.flashMessages.get("toast"),
},
errors
are automatically toasted, handled in thehandler.ts
file &main_layout.tsx
file.toast
is automatically toasted, handled in themain_layout.tsx
file.
You can use the user
property to get the user data inside your components.
const props = usePageProps();
const user = props.props.user;
Adding a new shared data
To add a new shared data, you can add it in the sharedData
property in the config/inertia.ts
file.
To make it type-safe in inertia, you have to go in the inertia/globals.d.ts
file and add the new shared data.
import type { Page, PageProps } from "@inertiajs/core";
import User from "#common/models/user";
interface SharedProps extends PageProps {
errors?: string | string[];
toast?: {type: 'success' | 'error', message: string};
user: User | undefined
}
export default SharedProps;
declare module "@inertiajs/react" {
export function usePage(): Page<SharedProps>;
}