Shared data

Sharing data

The server-side adapters provide a way to preassign shared data for each request. Shared data will be automatically merged with the page props provided in your controller.

This is done through the share() helper. It takes a dict and share this data in every request.

Page props and shared data are merged together, so be sure to namespace your shared data appropriately.

Via Middleware

app/http/middleware/HandleInertiaRequests.py
from masonite.inertia import InertiaMiddleware

class HandleInertiaRequests(InertiaMiddleware):
    
    def share(self, request):
    
         def get_auth():
             user = request.user()
             if user:
                 return user.serialize()
             else:
                 return None
                 
         return {"user": get_auth}

Here you can notice we don't directly share authenticated user but a callable returning authenticated user. This will allow to lazy load this prop when doing partial reloads.

On-the-fly

from masonite.provider import ServiceProvider
from masonite.auth import Auth


application.make("inertia").share({
    "user": "John",
})

Use this feature sparingly as shared data is included with every response.

Flash messages

In order for your server-side validation errors to be available client-side, Masonite adapter shares flash errors messages automatically through an errors prop.

It means that when you flash a message in session in your controller, the message will be available client-side (in your e.g. Vue.js component).

request.session.flash("errors", {"global": "An error has ocurred."})

With the React adapter, you could use the data like this:

const { errors } = useForm();
errors // == {global: "An error occured."}

If you want to update sharing flash messages logic you can override the share method in the HandleInertiaRequests middleware.

app/middleware/HandleInertiaRequests.py
class HandleInertiaRequests(InertiaMiddleware):
    
    def share(self, request):
        """Defines the props that are shared by default."""
        flashed_messages = request.session.get_flashed_messages()
        errors = flashed_messages.get("errors")
        success = flashed_messages.get("success")
        return {"errors": errors, "success": success}

Last updated