Overview

This tutorial will show you how to implement a Preact-based frontend for a user interface (UI) over a REST-based backend.

We'll concentrate here on the basics of the Preact UI frontend, for the details of the backend and the API, please check the plain JavaScript UI tutorial.

Build and try

  • If you've not already done so, clone the Mongoose Library repo

    $ git clone https://github.com/cesanta/mongoose
    
  • Build and run the example

    $ cd mongoose/examples/webui-preact
    $ make clean all
    
  • Go to http://localhost:8000 in your browser; the JavaScript code loads and executes, obtaining a configuration and rendering the page

browser
  • Change any parameter, it will be sent to the backend. You can also re-send any one of the values by clicking its "Update" button. Note that, since we don't have any update mechanism in place, yet, to get any possible configuration changes made by other users, you have to click the "Get configuration" button

Frontend implementation

The Preact framework is an alternative to React with the same modern API and a smaller footprint, ideal to fit on small devices with limited room for flash memory.

  • Once the JavaScript code is loaded by the browser, it will call the onload method, which will invoke Preact's render() method to execute the function App() and fill the HTML body section of the document.
  • The App() function, when first executed, invokes Preact's useEffect() hook, which tries to get the configuration by calling the fetch() method to GET /api/config/get, and then extracting the returned JSON object. If successful, it will store the configuration in a state variable by calling its appropriate set method
  • The returned HTML code will in fact include the execution of the function Configuration(), which gets passed the current configuration as a JSON object among its props.
  • This function initializes its local state variables with the values passed as arguments on call (or empty otherwise), and sets up the useEffect() hook to run on config changes and update those values. This will become handy when we add a way to get notified of configuration changes.
  • Each generated HTML input and button is configured to call its corresponding update function, while keeping the current value in its state variable
  • Each update function takes the corresponding value from the state variable and calls update(), that calls the fetch() method to POST to /api/config/set sending its arguments in the body as a stringified JSON object