optimist

Package Version Hex Docs

gleam add optimist@1

When building user interfaces, we are often faced with the question of what to do while waiting for a response from a server. One common pattern is to update the ui with an optimistic value - one we expect to get back if an operation is successful - and then update the ui again once we get an actual response.

This package, optimist, provides a simple way to manage this pattern through an Optimstic type and some functions to work with it. Let’s take a quick look at what you can do…

1. Start with a value

First things first, we need some value to be optimistic about!

let wibble = optimist.from(1)

2. Update it

We have two ways to perform optimistic updates on an Optimistic value:

let wobble = wibble |> optimist.push(2)
let wobble = wibble |> optimist.update(int.add(_, 1))

3. Do something with it

We’ve now performed an optimistic update and can render our value in the ui as if the operation has already succeeded.

html.p([], [
  html.text("Your value is: "),
  html.text(optimist.unwrap(wobble) |> int.to_string)
])

4. Resolve the update

We have a few different options for resolving an optimistic update depending on the situation:

let response = Ok(2)
let resolved = wibble |> optimist.resolve(response)
let response = Ok(1)
let resolved = wibble |> optimist.try(response, int.add)
let resolved = wibble |> optimist.revert
let resolved = wibble |> optimist.force
Search Document