DEV Community

Jeswin
Jeswin

Posted on

UI State Management for Forgo with Forgo-State

Forgo (forgojs.org) is a tiny UI library (less than 4KB) that makes it really simple to write Single Page Apps using JSX. I will not go into a detailed intro here, since you could get that on Forgo's website.

The examples on the website cover basic state management. But as applications grow more complex, you need a way to maintain application-wide state in a way similar to what Redux, MobX or React's Context/useReducer help you achieve.

Let's see how to do that in your Forgo app using forgo-state, a state-management library built on top of JavaScript Proxies. Just like forgo itself, forgo-state is tiny; less than 1KB gzipped.

First, define your state variables.

import { bindToStates, defineState } from "forgo-state";

const mailboxState = defineState({
  messages: [],
  drafts: [],
  spam: [],
});

const signinState = defineState({
  username: "",
  lastActive: 0,
});
Enter fullscreen mode Exit fullscreen mode

Now while defining the the component, bind it to one or more states using the bindToStates API.

function MailboxView() {
  const component = {
    render(props: any, args: ForgoRenderArgs) {
      return (
        <div>
          {state.messages.length ? (
            state.messages.map((m) => <p>{m}</p>)
          ) : (
            <p>There are no messages for {state.username}.</p>
          )}
        </div>
      );
    },
  };
  return bindToStates([mailboxState, signinState], component);
}
Enter fullscreen mode Exit fullscreen mode

That's it really. You're free to update the state variables any way you choose.

async function updateInbox() {
  const data = await fetchInboxData();
  // The next line causes a rerender of MailboxView
  mailboxState.messages = data;
}
Enter fullscreen mode Exit fullscreen mode

That's it really.

Hope you enjoyed the article, and don't forget to give Forgo a try.

Top comments (0)