Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions site/routes_how_tos.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ func setupHowTos(ctx context.Context, router chi.Router) error {
{ID: "how_to_load_more_list_items"},
{ID: "how_to_poll_the_backend_at_regular_intervals"},
{ID: "how_to_redirect_the_page_from_the_backend"},
{ID: "how_to_send_toast_notifications_from_the_backend"},
},
},
}
Expand Down
28 changes: 28 additions & 0 deletions site/routes_how_tos_toast.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package site

import (
"net/http"
"time"

"github.com/go-chi/chi/v5"
"github.com/starfederation/datastar/sdk/go/datastar"
)

func setupHowTosToast(howTosToast chi.Router) error {

howTosToast.Route("/toast/data", func(dataRouter chi.Router) {

dataRouter.Post("/", func(w http.ResponseWriter, r *http.Request) {
sse := datastar.NewSSE(w, r)
sse.MergeFragments(`
<li class="toast">Toasted</li>
`).WithSelector(`
#toaster
`).WithMergeMode(
Append
)
})
})

return nil
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
# How to send Toast Notifications from the backend

## Intro

A common usecase in modern web applications is to display toast notifications somewhere on the page to alert the user that an action they did worked,
or not. With Datastar, we can easily push the notifcation directly to our application without having to return some status code and then letting the
application react to those. Since we pilot our application from the backend, we can then notify the user using that same backend.

## Goal

Send a toast notification from the backend and have it appear on the page.

## Demo

<button data-on-click="@post('/how_tos/toast/data')" class="btn btn-primary font-bold">Cook!</button>
<ul id="toaster" style="position: absolute; right: 1em; bottom: 1em;"></ul>

## Steps

To display our toasts, we will need a toaster somewhere on the page. In the demo, the toaster is a simple `ul` with `id="toaster"`. We will then
append `li` on click, coming from the backend.

```html
<button data-on-click="@post('/create_user')">
Create
</button>
```

## Conclusion