Preact-based Web UI
This tutorial will show you how to implement a Preact-based frontend for a user interface (UI) over a REST-based backend.
Build and try
Follow the Build Tools tutorial to setup your development environment.
Start a terminal in the project directory; 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
- 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
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.
onloadmethod, which will invoke Preact's
render()method to execute the function
App()and fill the HTML
bodysection of the document.
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/setsending its arguments in the body as a stringified JSON object