sailscastshq / boring-stack

Ship JavaScript products with battle-tested technologies in days not weeks.
https://docs.sailscasts.com/boring-stack/getting-started
MIT License
390 stars 19 forks source link

Support flash messages #79

Closed DominusKelvin closed 6 months ago

DominusKelvin commented 6 months ago

Description

Flash messages are a stable and boring way to transfer messages from one page to the other leveraging session. For example, you want to "flash" a success, error, or even just a message from one action and then in another page you want to display that message.

With this implementation inertia-sails will leverage the new sails-flash hook and share a flash prop for every request. The signature of the flash prop is an object with 3 properties:

const flash = {
  success: [],
  error: [],
  message: []
}

With this implementation, in your pages you can then reference the flash prop like flash.success or use the usePage hook to get the flash prop. Here is an implementation from Hagfish that uses the flash messages in AppLayout so flash messages can be seen in the dashboard(my components are in Vue you can adjust accordingly for React or Svelte):

import { ref } from 'vue'
const messages = ref(usePage().props.flash.message)
const errors = ref(usePage().props.flash.error)
const successes = ref(usePage().props.flash.success)

Since flash always returns an array, we can loop like so:

<template>
  <main class="p-4 text-gray md:mx-auto md:mt-4 md:w-9/12 md:p-0 lg:w-7/12">
    <template v-for="message in messages">
      <Message severity="info">{{ message }}</Message>
    </template>
    <template v-for="error in errors">
      <Message severity="error">{{ error }}</Message>
    </template>
    <template v-for="success in successes">
      <Message severity="success">{{ success }}</Message>
    </template>
    <slot></slot>
  </main>
</template>