<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Tiago Peres França on Medium]]></title>
        <description><![CDATA[Stories by Tiago Peres França on Medium]]></description>
        <link>https://medium.com/@tiagoperesfr?source=rss-23b2489b87ba------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*70FV4MtKURcULzTT_ItHZw.jpeg</url>
            <title>Stories by Tiago Peres França on Medium</title>
            <link>https://medium.com/@tiagoperesfr?source=rss-23b2489b87ba------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 08:17:59 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@tiagoperesfr/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Building Server-Driven Mobile Apps With Nimbus SDUI]]></title>
            <link>https://medium.com/better-programming/building-server-driven-mobile-apps-with-nimbus-sdui-8b1102ab71d5?source=rss-23b2489b87ba------2</link>
            <guid isPermaLink="false">https://medium.com/p/8b1102ab71d5</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[server-driven-ui]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Tiago Peres França]]></dc:creator>
            <pubDate>Wed, 15 Mar 2023 17:27:41 GMT</pubDate>
            <atom:updated>2023-03-15T17:27:41.355Z</atom:updated>
            <content:encoded><![CDATA[<h4>A to-do app driven by the backend with Nimbus SDUI</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*56P-YqYA-X6c4KJB5ivRsQ.png" /><figcaption>A window with the code to the backend with a screenshot of the result on both iOS (left) and Android (right).</figcaption></figure><p><a href="https://medium.com/better-programming/announcing-nimbus-server-driven-ui-beta-9a0d95686fd9">Last time,</a> we gave an overall on how Nimbus can help with creating server-driven content for your mobile application. This time, we’re gonna get our hands dirty and use some actual code to build a To Do App where the user interface (UI) is completely driven by the backend.</p><p>The application we will build can be seen in the video below:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FbfQ7oL2qzNU%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DbfQ7oL2qzNU&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FbfQ7oL2qzNU%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/bb7fc49d418162b9dcb38b57b3c7c3de/href">https://medium.com/media/bb7fc49d418162b9dcb38b57b3c7c3de/href</a></iframe><p>This is a long article, and I divided it into four checkpoints. Once you reach a checkpoint, it might be time to give it a pause, grab a snack, and come back later. This is a coding tutorial, so it&#39;s important that you&#39;re able to compare your source code with the expected source code. For this reason, we have a <a href="https://github.com/Tiagoperes/nimbus-todo-app">repository</a> with four different branches. At checkpoint 1, you can validate your code with the branch “part 1,” at checkpoint 2, you can validate it with the branch “part 2,” and so on.</p><p>This article will always present one “how to” for Android and another for iOS. If you&#39;re interested in only one of these platforms, you can safely skip the sections for the other.</p><h3>Creating the Android Project</h3><ol><li>Use Android Studio to create a new Android Project with Jetpack Compose.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/891/1*4kAJqtAbvINk19NnRScZRg.png" /><figcaption>Empty Compose Activity</figcaption></figure><p>2. Name your project, set the minimum Android API, and click finish.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/892/1*5WbSC91znYryWk7n2hN0eA.png" /><figcaption>Name: To Do App. Package name: com.todoapp; Minimum SDK: API 21.</figcaption></figure><p>3. To use all Nimbus dependencies, add the following code to your app/build.gradle file:</p><pre>plugins {<br>    // Support for auto-deserialization in Nimbus<br>    id &#39;com.google.devtools.ksp&#39; version &quot;1.7.0-1.0.6&quot; // use the latest version of KSP according to your Kotlin version<br>}<br><br>dependencies {<br>    // Compose navigation<br>    implementation (&quot;androidx.navigation:navigation-compose:2.5.1&quot;)<br>    // Nimbus compose base library<br>    implementation &#39;br.com.zup.nimbus:nimbus-compose:1.0.0-beta1&#39;<br>    // Layout components for Nimbus<br>    implementation &#39;br.com.zup.nimbus:nimbus-layout-compose:1.0.0-beta1&#39;<br>    // Support for auto-deserialization<br>    implementation &#39;br.com.zup.nimbus:nimbus-compose-annotation:1.0.0-beta1&#39;<br>    ksp &#39;br.com.zup.nimbus:nimbus-compose-processor:1.0.0-beta1&#39;<br>}<br><br>// Support for auto-deserialization<br>kotlin {<br>    sourceSets.debug {<br>        kotlin.srcDir(&quot;build/generated/ksp/debug/kotlin&quot;)<br>    }<br>    sourceSets.release {<br>        kotlin.srcDir(&quot;build/generated/ksp/release/kotlin&quot;)<br>    }<br>    sourceSets.test {}<br>}</pre><p>As of the time of writing, all dependencies are at version 1.0.0-beta1, you should always use the latest version.</p><p>4. Sync your project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/819/1*9kyt-z3l9fUH2lb5XtkB3g.png" /><figcaption>Gradle’s elephant icon in the toolbar</figcaption></figure><p>5. Add internet permissions by including the following code to your manifest file (app/src/main/AndroidManifest.xml):</p><pre>&lt;manifest xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br>    xmlns:tools=&quot;http://schemas.android.com/tools&quot;&gt;<br>    &lt;uses-permission android:name=&quot;android.permission.INTERNET&quot; /&gt;<br>    &lt;uses-permission android:name=&quot;android.permission.ACCESS_NETWORK_STATE&quot; /&gt;<br>&lt;/manifest&gt;</pre><p>6. Now, we need to create an instance of Nimbus. For this, create a new source code file called Nimbus.kt and add the following code to it:</p><pre>package com.todoapp<br><br>import br.com.zup.nimbus.compose.Nimbus<br>import br.com.zup.nimbus.compose.NimbusMode<br>import br.com.zup.nimbus.compose.layout.layoutUI<br><br>const val BASE_URL = &quot;https://gist.githubusercontent.com/Tiagoperes/da38171c94be043c3e5b81cbb835a0e5/raw/ab832ba276764f4de12552f02c4f56e20cd83b0b&quot;<br><br>val nimbus = Nimbus(<br>    baseUrl = BASE_URL,<br>    ui = listOf(layoutUI),<br>    mode = if (BuildConfig.DEBUG) NimbusMode.Development else NimbusMode.Release,<br>)</pre><ul><li>Nimbus is the class that provides server-driven UI to the application. It holds all configurations and internal services required by Nimbus.</li><li>baseUrl is the url for the backend server providing the server-driven screens. Since we don’t have a backend yet, we&#39;ll use a JSON file hosted on Github (Gist).</li><li>ui is the list of UI libraries we intend to use in our application. A UI Library consists mainly of components (composable functions) and can also contain Nimbus actions and Nimbus operations. Since we don’t have any customization yet, we&#39;ll just use the layout library.</li><li>mode is a configuration to tell Nimbus which environment the app is on: if in development mode, Nimbus will render errors to the screen, otherwise, it will just not render the component with an error. Since BuildConfig is a generated file, you need to build the project before Android Studio recognizes it.</li></ul><p>7. Use Jetpack Compose to provide the nimbus instance you just created to the UI tree. In MainActivity.kt:</p><pre>// ...<br>import br.com.zup.nimbus.compose.ProvideNimbus<br><br>class MainActivity : ComponentActivity() {<br>    override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br>        setContent {<br>            ToDoAppTheme {<br>                // A surface container using the &#39;background&#39; color from the theme<br>                Surface(<br>                    modifier = Modifier.fillMaxSize(),<br>                    color = MaterialTheme.colors.background<br>                ) {<br>                    // Providing the nimbus configuration to the UI tree<br>                    ProvideNimbus(nimbus) {<br>                        // your content goes here. Every node from here and on will use the provided nimbus instance<br>                        Greeting(&quot;Android&quot;)<br>                    }<br>                }<br>            }<br>        }<br>    }<br>}<br><br>// ...</pre><p>Above, we used ProvideNimbus to enable SDUI in our UI tree.</p><p>8. Now, to load a view from the backend, we just need to replace the current content (Greeting(&quot;Android&quot;)) with the NimbusNavigator.</p><pre>// ...<br>import br.com.zup.nimbus.compose.NimbusNavigator<br>import br.com.zup.nimbus.compose.ProvideNimbus<br>import br.com.zup.nimbus.core.network.ViewRequest<br><br>// ...<br><br>ProvideNimbus(nimbus) {<br>    // your content goes here. Every node from here and on will use the provided nimbus instance<br>    NimbusNavigator(ViewRequest(&quot;/hello-world.json&quot;))<br>}<br><br>// ...</pre><p>The Nimbus Navigator will render the UI described by the JSON at “<em>$baseUrl</em>/hello-world.json,” i.e., “<a href="https://gist.githubusercontent.com/Tiagoperes/da38171c94be043c3e5b81cbb835a0e5/raw/ab832ba276764f4de12552f02c4f56e20cd83b0b/hello-world.json">https://gist.githubusercontent.com/Tiagoperes/da38171c94be043c3e5b81cbb835a0e5/raw/ab832ba276764f4de12552f02c4f56e20cd83b0b/hello-world.json</a>.”</p><p>9. Run the project, you should see a text saying “Hello World.”</p><h3>Creating the iOS Project</h3><ol><li>Use XCode to create a new project with SwiftUI.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/716/1*ZyAwPJD1gHCsmr3k6TcPTQ.png" /><figcaption>iOS &gt; App</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/713/1*DEYXJYp-YZjHTdZHluupNg.png" /><figcaption>Product Name: To Do App. Organization Identifier: todoapp. Interface: SwiftUI. Language: Swift.</figcaption></figure><p>2. Choose a location for the project and click the button to finish.</p><p>3. Select the menu option File &gt; Add Packages. Choose the option to load the package via GitHub. Use the address “<a href="https://github.com/ZupIT/nimbus-layout-swiftui.git">https://github.com/ZupIT/nimbus-layout-swiftui.git</a>,” and, for the version, use “exact” typing the latest beta build (1.0.0-beta.1 at the time of writing).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WUS8_thl7pEiAdRn73Z1Yw.png" /><figcaption>Adding the dependency nimbus-layout-swiftui at 1.0.0-beta.1.</figcaption></figure><p>4. Now that Nimbus is installed, let’s use it to create our UI tree. Replace the content of ContentView.swift with the following code:</p><pre>import SwiftUI<br>import NimbusSwiftUI<br>import NimbusLayoutSwiftUI<br><br>let baseUrl = &quot;https://gist.githubusercontent.com/Tiagoperes/da38171c94be043c3e5b81cbb835a0e5/raw/ab832ba276764f4de12552f02c4f56e20cd83b0b&quot;<br><br>struct ContentView: View {<br>  var body: some View {<br>    Nimbus(baseUrl: baseUrl) {<br>      // construct your view hierarchy containing a navigator here<br>      VStack {<br>        Image(systemName: &quot;globe&quot;)<br>            .imageScale(.large)<br>            .foregroundColor(.accentColor)<br>        Text(&quot;Hello, world!&quot;)<br>      }<br>      .padding()<br>    }<br>    .ui([layout])<br>  }<br>}</pre><ul><li>Nimbus is a component that provides Server Driven UI to the application. It holds all configurations and internal services required by Nimbus. Every child of this component will use this server-driven UI configuration. Each configuration other than the baseUrl is passed to Nimbus the same way we add modifiers to a SwiftUI component, i.e., with the dot operator.</li><li>baseUrl is the url for the backend server providing the server-driven screens. Since we don’t have a backend yet, we’ll use a JSON file hosted in Github (Gist).</li><li>ui is the list of UI libraries we intend to use in our application. A UI Library consists mainly of components (View structs) and can also contain Nimbus actions and Nimbus operations. Since we don’t have any customization yet, we&#39;ll just use the layout library.</li></ul><p>5. Replace the default content with the NimbusNavigator, which loads a server-driven UI from the backend.</p><pre>Nimbus(baseUrl: baseUrl) {<br>  NimbusNavigator(url: &quot;/hello-world.json&quot;)<br>}</pre><p>The Nimbus Navigator will render the UI described by the JSON at “<em>$baseUrl</em>/hello-world.json”, i.e.,</p><p><a href="https://gist.githubusercontent.com/Tiagoperes/da38171c94be043c3e5b81cbb835a0e5/raw/ab832ba276764f4de12552f02c4f56e20cd83b0b/hello-world.json">https://gist.githubusercontent.com/Tiagoperes/da38171c94be043c3e5b81cbb835a0e5/raw/ab832ba276764f4de12552f02c4f56e20cd83b0b/hello-world.json</a>.</p><p>6. Run the project, you should see a text saying “Hello World.”</p><h3>Creating the Backend Project</h3><p>The backend can either be done with plain JSONs or with a backend server that generates the JSONs. In this tutorial, we&#39;ll go with the latter. This section shows how to create a backend project for Nimbus using Node.js and TypeScript.</p><ol><li>If you don’t have <a href="https://nodejs.org/en/">Node</a> installed, install it. Nimbus requires at least version 13.2.</li><li>If you don’t have <a href="https://yarnpkg.com/">Yarn</a> installed, install it. Yarn is a dependency management tool used by the Nimbus CLI.</li></ol><pre>npm install yarn --global</pre><p>3. Install the Nimbus backend CLI:</p><pre>yarn global add @zup-it/nimbus-backend-cli</pre><p>4. With the CLI tool installed, change to the directory where you want the project to be created and type:</p><pre>nimbus-ts new todo-app-backend</pre><p>5. The project will be created under /todo-app-backend. Change to this directory and run:</p><pre>yarn start</pre><p>6. The backend will be running at <a href="http://localhost:3000.">http://localhost:3000.</a> This address provides a default JSON with a welcome message.</p><h3>Linking the Client Applications to the Backend</h3><p>It suffices to alter the baseUrl of the Nimbus configuration to change the backend. Since we want to load the root address as a server-driven view, we also need to alter the navigator’s address to /.</p><p>Android: Nimbus.kt</p><pre>const val BASE_URL = &quot;http://10.0.2.2:3000&quot;</pre><p>Android: MainActivity.kt</p><pre>NimbusNavigator(ViewRequest(&quot;/&quot;))</pre><p>iOS: ContentView.swift</p><pre>let baseUrl = &quot;http://127.0.0.1:3000&quot;<br><br>struct ContentView: View {<br>  var body: some View {<br>    Nimbus(baseUrl: baseUrl) {<br>      NimbusNavigator(url: &quot;/&quot;)<br>    }<br>    .ui([layout])<br>  }<br>}</pre><p>Rerun both apps. They should now show the UI provided by our backend. This is a simple screen with a welcome message and simple navigation between two pages.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4mKlmMHXxm6e0iQTo-VGuQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6lna7n486KJ72O3tWoqZiA.png" /><figcaption>Android result on the left. iOS result on the right.</figcaption></figure><p>You can now alter your backend as you wish and change the app&#39;s content without rebuilding the application!</p><p>Every time you need the content to be server driven, you can add a new NimbusNavigator. If you need two different Server Driven UI configurations, you can use multiple NimbusProviders.</p><h3>Editing the Backend Application To List All To Do Notes</h3><p>We recommend using <a href="https://code.visualstudio.com/">VS Code</a> to edit the backend code. If you don&#39;t have it installed yet, please do so.</p><p>1. Open the backend project in VSCode</p><p>2. Since we&#39;re going to be dealing with To Do Notes, we need to first understand their structure. If you didn’t watch the video with the final app, go back and watch it. Notice that we don&#39;t simply list the notes, instead, we also group them by date. For this reason, there are two data structures we need to type: the Note itself and the NoteSection, which represents a date and the notes in it. The service to list the notes will always return a <a href="https://gist.githubusercontent.com/Tiagoperes/3888902b98494708202fa05569444451/raw/dbc705192e2f87233da2f1eec35936aef8125545/todo.json">list of </a><a href="https://gist.githubusercontent.com/Tiagoperes/3888902b98494708202fa05569444451/raw/dbc705192e2f87233da2f1eec35936aef8125545/todo.json">NoteSections</a> and not a list of Notes. To write these types, create the file src/types.ts with the following content:</p><pre>export interface NoteSection {<br>  date: number,<br>  items: Note[],<br>}<br><br>export interface Note {<br>  id: number,<br>  title: string,<br>  description: string,<br>  date: number,<br>  isDone: boolean,<br>}</pre><p>3. Let’s write the screen now: create the file src/screens/todo-list.tsx with the following content:</p><pre>import { createState, NimbusJSX, If, Then, Else, ForEach } from &#39;@zup-it/nimbus-backend-core&#39;<br>import { sendRequest, log } from &#39;@zup-it/nimbus-backend-core/actions&#39;<br>import { Screen } from &#39;@zup-it/nimbus-backend-express&#39;<br>import { Lifecycle, Text, Column } from &#39;@zup-it/nimbus-backend-layout&#39;<br>import { NoteSection } from &#39;../types&#39;<br><br>export const ToDoList: Screen = () =&gt; {<br>  const isLoading = createState(&#39;isLoading&#39;, true)<br>  const notes = createState&lt;NoteSection[]&gt;(&#39;notes&#39;, [])<br><br>  const loadItems = sendRequest&lt;NoteSection[]&gt;({<br>    url: &quot;https://gist.githubusercontent.com/Tiagoperes/3888902b98494708202fa05569444451/raw/dbc705192e2f87233da2f1eec35936aef8125545/todo.json&quot;,<br>    onSuccess: response =&gt; notes.set(response.get(&#39;data&#39;)),<br>    onError: response =&gt; log({ level: &#39;error&#39;, message: response.get(&#39;message&#39;) }),<br>    onFinish: isLoading.set(false),<br>  })<br><br>  return (<br>    &lt;Lifecycle onInit={loadItems} state={[isLoading, notes]}&gt;<br>      &lt;If condition={isLoading}&gt;<br>        &lt;Then&gt;&lt;Text&gt;Loading&lt;/Text&gt;&lt;/Then&gt;<br>        &lt;Else&gt;<br>          &lt;Column&gt;<br>            &lt;ForEach items={notes} key=&quot;date&quot;&gt;<br>              {(section) =&gt; (<br>                &lt;Column marginTop={5}&gt;<br>                  &lt;Text weight=&quot;bold&quot;&gt;{section.get(&#39;date&#39;)}&lt;/Text&gt;<br>                  &lt;ForEach items={section.get(&#39;items&#39;)} key=&quot;id&quot;&gt;<br>                    {(item) =&gt; &lt;Text&gt;{item.get(&#39;title&#39;)}&lt;/Text&gt;}<br>                  &lt;/ForEach&gt;<br>                &lt;/Column&gt;<br>              )}<br>            &lt;/ForEach&gt;<br>          &lt;/Column&gt;<br>        &lt;/Else&gt;<br>      &lt;/If&gt;<br>    &lt;/Lifecycle&gt;<br>  )<br>}</pre><p>We’re not going into every detail of the backend code here, for this, we recommend the <a href="https://github.com/ZupIT/nimbus-docs/blob/main/backend-ts/index.md">documentation</a>. Instead, we’ll make a general explanation and link the generated JSON.</p><p>In this screen, we have two states: isLoading and notes. isLoading indicates the status of the request to the API of Notes while notes stores the result of the request.</p><p>With the action <a href="https://github.com/ZupIT/nimbus-docs/blob/main/specification/default-actions/send-request.md">sendRequest</a> attached to the event onInit of the component <a href="https://gist.github.com/Tiagoperes/694516d05bf989cb0a222dd03c8f4537#file-layout-ts-L135">Lifecycle</a>, we can send the request to list the notes as soon as the view is loaded. We&#39;ll not use the notes API yet. Instead, we&#39;ll load the notes from a static JSON hosted in GitHub. Once the request succeeds, we set the state notes with the response&#39;s data (body). If the request fails, we log an error message, and when the request finishes, we set the state isLoading to false.</p><p>Since this is a Screen, it returns the UI tree. For now, we have a very simple UI that checks the value of isLoading and either displays the text &quot;Loading&quot; or displays a List with every NoteSection and its notes. To iterate over a List, we use the component <a href="https://github.com/ZupIT/nimbus-docs/blob/main/specification/default-components/for-each.md">ForEach</a>, which needs the items to iterate over and a key. The key must be the property that identifies each item. The content of a ForEach component will always be a function that receives the current item as a parameter and returns the UI for it.</p><p>4. To make this screen accessible, replace the contents of src/screens/index.ts with:</p><pre>import { RouteMap } from &#39;@zup-it/nimbus-backend-express&#39;<br>import { ToDoList } from &#39;./todo-list&#39;<br><br>export const routes: RouteMap = {<br>  &#39;&#39;: ToDoList,<br>}</pre><p>5. You can now remove the boilerplate files src/screens/home.tsx and src/screens/welcome.tsx.</p><p>6. Access <a href="http://localhost:3000,">http://localhost:3000,</a> it should load the <a href="https://gist.github.com/Tiagoperes/f445a78c1296016d00937fdedaaec09c#file-todo-list-json">JSON for the screen you just created</a>.</p><p>7. Rerun the client app. You should see a list of To Do Notes grouped by date. The dates are still unformatted (Longs), but we&#39;ll deal with this later.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/243/1*WXqKXptoemjtDSCSNRklEQ.png" /></figure><p><strong>Attention:</strong> if you get a network error on Android, it’s probably because Android is complaining about using HTTP instead of HTTPS. To solve this, create the file <a href="https://github.com/Tiagoperes/nimbus-todo-app/blob/part1/android/app/src/main/res/xml/network_security_config.xml">res/xml/network_security_config.xml</a> and add android:networkSecurityConfig=&quot;@xml/network_security_config to the tag “application” of your <a href="https://github.com/Tiagoperes/nimbus-todo-app/blob/part1/android/app/src/main/AndroidManifest.xml">AndroidManifest.xml</a>.</p><h3>Checkpoint 1</h3><p>You just reached the first checkpoint! You can verify your current code with the <a href="https://github.com/Tiagoperes/nimbus-todo-app/tree/part1">branch “part 1” of the GitHub repository</a>. Next, we&#39;ll focus on transforming this raw data into a beautiful UI.</p><h4>Check the image below:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D1kwdJQj_Q_E3rnCWWurUQ.png" /></figure><p>We can use the default layout library to implement most of this UI, but there are some special components that depend on the design system of the App and must have custom implementations. In the screen above, we can notice the following custom components:</p><ul><li>An icon, to show the search and delete icons.</li><li>A text input for the search feature.</li><li>A selection component to choose between the options “All,” “To Do, and “Done.”</li><li>A button to make the circular button with a “plus” sign.</li></ul><p>Now that we identified which components we need to implement, we must define their contract, i.e., namespace, name, and properties. As the namespace, we’ll use todoapp. See the list below for the name and properties of each component:</p><p>icon</p><ul><li>name: a string containing the identifier for the icon.</li><li>color: an optional string telling the color of the icon.</li><li>size: an optional integer telling the size of the icon.</li></ul><p>textInput</p><ul><li>label: a string containing the label of the input.</li><li>value: an optional string with the current value of the input.</li><li>color: an optional string with the color of the input.</li><li>onChange: an event, i.e., a property that must receive a list of Nimbus Actions, which will be run once the event is triggered. This event is always triggered with the current value as a parameter.</li></ul><p>selectionGroup</p><ul><li>options: a list of strings with every option available.</li><li>value: a string with the current value must be one of the options.</li><li>onChange: an event, i.e., a property that must receive a list of Nimbus Actions, which will be run once the event is triggered. This event is always triggered with the current value as a parameter.</li></ul><p>circularButton</p><ul><li>icon: a string containing the identifier for the icon to show inside the button.</li><li>onPress: an event, i.e., a property that must receive a list of Nimbus Actions, which will be run once the event is triggered.</li></ul><p>Now that we have defined every component to build the main screen of our To Do App, let’s implement them in each one of the projects! Keep in mind that it is not the goal of this tutorial to teach SwiftUI, Compose, or JSX, so we&#39;ll only focus on the code regarding Nimbus.</p><h3>Custom Components on Android</h3><ol><li>Create a package called component and, under it, create the files: Icon.kt, TextInput.kt, SelectionGroup.kt, and CircularButton.kt.</li><li>All components follow the same implementation logic. Create the composable function just like any other composable component and then annotate it with @AutoDeserialize. A difference to common composable functions is that you shouldn&#39;t use default values other than null in the function parameters (this is due to the inability of an annotation processor to see the default value of a parameter).</li><li>Let’s see the implementation for the TextInput:</li></ol><pre>import androidx.compose.foundation.layout.fillMaxWidth<br>import androidx.compose.material.Text<br>import androidx.compose.material.TextField<br>import androidx.compose.material.TextFieldDefaults<br>import androidx.compose.runtime.Composable<br>import androidx.compose.ui.Modifier<br>import androidx.compose.ui.graphics.Color<br>import br.com.zup.nimbus.annotation.AutoDeserialize<br><br>@Composable<br>@AutoDeserialize<br>fun TextInput(<br>    label: String,<br>    value: String? = null,<br>    onChange: (value: String) -&gt; Unit,<br>    color: Color? = null,<br>) {<br>    val textFieldColor = color ?: Color.DarkGray<br>    TextField(<br>        value = value ?: &quot;&quot;,<br>        onValueChange = onChange,<br>        label = { Text(label) },<br>        modifier = Modifier.fillMaxWidth(),<br>        colors = TextFieldDefaults.textFieldColors(<br>            backgroundColor = Color.Transparent,<br>            textColor = textFieldColor,<br>            focusedIndicatorColor = Color.Transparent,<br>            unfocusedIndicatorColor = Color.Transparent,<br>            focusedLabelColor = textFieldColor,<br>            unfocusedLabelColor = textFieldColor,<br>            cursorColor = textFieldColor,<br>        )<br>    )<br>}</pre><p>As you can see, besides the annotation, we don&#39;t need anything special to make this component compatible with server-driven views. Nimbus annotation processor will check every parameter and, in build time, generate an intermediary composable that is able to deserialize all properties from the JSON into the types required by the composable function you implemented.</p><p>Notice that, for events, we&#39;ll always have lambdas. In this case, where the event provides a value, the lambda must have a parameter.</p><p>If you try to run this code, you&#39;ll get an error from the annotation processor regarding the type Color. Nimbus can figure out how to deserialize primitive types and classes consisting of properties with primitive types. This is not the case for Color, so we must create a custom deserializer for it.</p><p>4. To create a custom deserializer for Color, add the file ColorDeserializer.kt to a new package called deserialization. This file must contain the following code:</p><pre>import androidx.compose.ui.graphics.Color<br>import br.com.zup.nimbus.annotation.Deserializer<br>import br.com.zup.nimbus.compose.layout.extensions.color<br>import br.com.zup.nimbus.core.deserialization.AnyServerDrivenData<br><br>@Deserializer<br>fun deserializeColor(data: AnyServerDrivenData): Color? = data.asStringOrNull()?.color</pre><p>A deserializer is a function annotated with @Deserializer that receives an object of unknown type wrapped in the class AnyServerDrivenData. This object can be read into the expected type and converted. In this case, we just used an extension function of the layout package that transforms a string into a Color object.</p><p>Now that the deserializer is created, we can use the type <em>Color? </em>whenever we need it!</p><p>5. In Nimbus.kt, create a new UI Library to register the newly created component (TextInput):</p><pre>import androidx.compose.runtime.Composable<br>import br.com.zup.nimbus.compose.Nimbus<br>import br.com.zup.nimbus.compose.NimbusMode<br>import br.com.zup.nimbus.compose.layout.layoutUI<br>import br.com.zup.nimbus.compose.ui.NimbusComposeUILibrary<br>import com.todoapp.component.TextInput<br><br>const val BASE_URL = &quot;http://10.0.2.2:3000&quot;<br><br>private val todoAppUI = NimbusComposeUILibrary(&quot;todoapp&quot;)<br>    .addComponent(&quot;textInput&quot;) @Composable { TextInput(it) }<br><br>val nimbus = Nimbus(<br>    baseUrl = BASE_URL,<br>    ui = listOf(layoutUI, todoAppUI),<br>    mode = if (BuildConfig.DEBUG) NimbusMode.Development else NimbusMode.Release,<br>)</pre><p>Notice that we created a new UI library with the namespace todoapp. We’re going to add every component, operation, and action we create to this UI Library. We also added it to the Nimbus Configuration.</p><p><strong>Attention</strong>: TextInput(it) calls a code that is generated at build time. For the IDE to recognize it, rebuild the project.</p><p>6. The TextInput is the most complex of the components we need to implement, mainly because it requires a custom deserializer. All other components are straightforward and won&#39;t be explained here. Use the links below to copy and paste the code to your project.</p><ul><li><a href="https://github.com/Tiagoperes/nimbus-todo-app/blob/part2/android/app/src/main/java/com/todoapp/component/Icon.kt">components/Icon.kt</a></li><li><a href="https://github.com/Tiagoperes/nimbus-todo-app/blob/part2/android/app/src/main/java/com/todoapp/component/SelectionGroup.kt">components/SelectionGroup.kt</a></li><li><a href="https://github.com/Tiagoperes/nimbus-todo-app/blob/part2/android/app/src/main/java/com/todoapp/component/CircularButton.kt">components/CircularButton.kt</a></li><li><a href="https://github.com/Tiagoperes/nimbus-todo-app/blob/part2/android/app/src/main/java/com/todoapp/Nimbus.kt">Nimbus.kt</a></li></ul><h3>Custom Components on iOS</h3><ol><li>Create a new folder called Components and, under it, create the files Icon.swift, TextInput.swift, SelectionGroup.swift, and CircularButton.swift.</li><li>All components follow the same implementation logic. Create the SwiftUI component just like any other View struct, make it conform to Decodable, and add Property Wrappers to events if they exist in the component. The only difference to common SwiftUI components is that you should not use default values for the properties of the struct.</li><li>Let’s see the implementation for the TextInput:</li></ol><pre>import SwiftUI<br>import NimbusSwiftUI<br><br>private let defaultColor = Color(red: 97/255, green: 107/255, blue: 118/255)<br><br>struct TextInput: View, Decodable {<br>  var label: String<br>  var value: String?<br>  var color: Color?<br>  @StatefulEvent var onChange: (String) -&gt; Void<br><br>  var body: some View {<br>    let binding = Binding(<br>        get: { value ?? &quot;&quot; },<br>        set: {<br>          onChange($0)<br>        }<br>    )<br>    VStack(alignment: .leading) {<br>      if (color == nil) {<br>        TextField(label, text: binding).foregroundColor(defaultColor)<br>      } else {<br>        ZStack(alignment: .leading) {<br>          if (value?.isEmpty != false) { Text(label).foregroundColor(color) }<br>          TextField(&quot;&quot;, text: binding)<br>            .foregroundColor(color)<br>            .accentColor(color)<br>        }<br>      }<br>    }.padding(16)<br>  }<br>}</pre><p>A TextField from SwiftUI expects a binding. Nimbus doesn&#39;t work with the concept of bindings, but a binding is nothing more than the combination of a readable value and a function to alter the next value to read, i.e., the properties value and onChange of our component. To comply with SwiftUI&#39;s TextField, we create a binding from these properties.</p><p>Another interesting part of the code is the property wrapper @StatefulEvent. Whenever we have a property that represents an event, we must annotate it with @Event or @StatefulEvent depending if the event is parameterized or not.</p><p>If you’re also checking the code for Android, you&#39;ll notice that we didn&#39;t create a special deserializer for the type Color. This is because the layout package already handles this type for us.</p><p>4. In ContentView.swift creates a new UI Library to register the newly created component (TextInput):</p><pre>import SwiftUI<br>import NimbusSwiftUI<br>import NimbusLayoutSwiftUI<br><br>let baseUrl = &quot;http://127.0.0.1:3000&quot;<br><br>let todoAppUI = NimbusSwiftUILibrary(&quot;todoapp&quot;)<br>  .addComponent(&quot;textInput&quot;, TextInput.self)<br><br>struct ContentView: View {<br>  var body: some View {<br>    Nimbus(baseUrl: baseUrl) {<br>      NimbusNavigator(url: &quot;/&quot;)<br>    }<br>    .ui([layout, todoAppUI])<br>  }<br>}</pre><p>Notice that we created a new UI library with the namespace todoapp. We’re going to add every component, operation, and action we create to this UI Library. We also added it to the Nimbus Configuration.</p><p>The TextInput is the most complex of the components we need to implement. All other components are straightforward and won’t be explained here. Use the links below to copy and paste the code to your project.</p><ul><li><a href="https://github.com/Tiagoperes/nimbus-todo-app/blob/part2/ios/To%20Do%20App/Components/Icon.swift">Components/Icon.swift</a></li><li><a href="https://github.com/Tiagoperes/nimbus-todo-app/blob/part2/ios/To%20Do%20App/Components/SelectionGroup.swift">Components/SelectionGroup.swift</a></li><li><a href="https://github.com/Tiagoperes/nimbus-todo-app/blob/part2/ios/To%20Do%20App/Components/CircularButton.swift">Components/CircularButton.swift</a></li><li><a href="https://github.com/Tiagoperes/nimbus-todo-app/blob/part2/ios/To%20Do%20App/ContentView.swift">ContentView.swift</a></li></ul><h3>Custom Components for the Backend</h3><p>If you&#39;re not using any backend tool for writing the JSON, then you don’t need to do anything, you can refer to the components we just implemented by using the format namespace:name, e.g., todoapp:textInput.</p><p>Since we&#39;re using a Node Backend, we need to use the Nimbus Backend Typescript library to declare these components as JSX tags.</p><p>Create the file TextInput.tsx under a new directory called components. Use the following code for its content:</p><pre>import { NimbusJSX, FC, Actions, Expression, State, createStateNode } from &#39;@zup-it/nimbus-backend-core&#39;<br>import { namespace } from &#39;../constants&#39;<br><br>interface Props {<br>  label: Expression&lt;string&gt;,<br>  value?: Expression&lt;string&gt;,<br>  color?: Expression&lt;string&gt;,<br>  onChange: (value: State&lt;string&gt;) =&gt; Actions,<br>}<br><br>export const TextInput: FC&lt;Props&gt; = ({ id, state, onChange, ...props }) =&gt; &lt;component<br>  namespace={namespace}<br>  name=&quot;textInput&quot;<br>  id={id}<br>  state={state}<br>  properties={{ onChange: onChange(createStateNode(&#39;onChange&#39;)), ...props }}<br>/&gt;</pre><p>If you ever worked with React, this is not too different. We first declare the component&#39;s type, and then we declare a Functional Component (FC) that builds the UI for it.</p><p>The interface, Props, includes some new types. Let&#39;s see what they mean:</p><ul><li>Expression&lt;T&gt;: this value can be either of type T or an expression in Nimbus Script that results in something of type T.</li><li>State&lt;T&gt;: this value must be a state that holds a value of type T.</li><li>Actions: a Nimbus Action or a list of Nimbus Actions.</li></ul><p>If you&#39;re not sure what are states, actions, or expressions, please, check our <a href="https://github.com/ZupIT/nimbus-docs/blob/main/specification/index.md">documentation</a>.</p><p>In HTML, we have a lot of intrinsic elements: div, p, table, span, etc. In Nimbus JSX, on the other hand, we have just one: component, which is the main tag for Nimbus and is transformed into a server-driven component when serialized into JSON. Example of a serialized component: _component: todoapp:textInput.</p><p>namespace is a constant imported from another file. Please create the file src/constants.ts and set the value of namespace to todoapp.</p><p>The function createStateNode(name: string) just creates a State object that refers to the name passed as a parameter. When you use the State object created with this function, it gets serialized into @{name} in the JSON.</p><p>All other components are created using the same logic: create the component&#39;s contract with a type definition and declare its namespace and name. Use the links below to copy and paste the code for each component of your project.</p><ul><li><a href="https://github.com/Tiagoperes/nimbus-todo-app/blob/part2/backend/src/components/Icon.tsx">components/Icon.tsx</a></li><li><a href="https://github.com/Tiagoperes/nimbus-todo-app/blob/part2/backend/src/components/SelectionGroup.tsx">components/SelectionGroup.tsx</a></li><li><a href="https://github.com/Tiagoperes/nimbus-todo-app/blob/part2/backend/src/components/CircularButton.tsx">components/CircularButton.tsx</a></li></ul><h3>Creating the UI for the Header in the Backend</h3><p>Now that we have all the components we need implemented, we can use them to build the UI in the backend. Open the file src/screens/todo-list.tsx and let&#39;s start by creating the header:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HmzuphVt5g0ZewTIYTo9TA.png" /></figure><p>Here we have a Row with three items centered in the vertical axis: an Icon, a TextInput, and a SelectionGroup. After placing the icon and selection group, the text input expands in the horizontal axis to fill up the remaining space.</p><p>We need two new states: one to keep track of the search term typed into the search field and another to store the visibility option (all, to do, or done). We&#39;ll name these states searchTerm and doneFilter, respectively. Check the code below for creating these states:</p><pre>const searchTerm = createState(&#39;searchTerm&#39;, &#39;&#39;)<br>const doneFilter = createState&lt;&#39;All&#39; | &#39;To do&#39; | &#39;Done&#39;&gt;(&#39;doneFilter&#39;, &#39;All&#39;)</pre><p>The first parameter of createState is the state name, and the second is the initial value. The generics (&lt;&gt;) tells the state type and must be explicitly declared only when inferring it from the second parameter is impossible.</p><p>We use the default layout components plus our custom components to declare the UI for the header:</p><pre>const header = (<br>  &lt;Row backgroundColor=&quot;#5F72C0&quot; crossAxisAlignment=&quot;center&quot; paddingHorizontal={20} height={65}&gt;<br>    &lt;Icon name=&quot;search&quot; color=&quot;#FFFFFF&quot; size={28} /&gt;<br>    &lt;Row width=&quot;expand&quot;&gt;<br>      &lt;TextInput color=&quot;#FFFFFF&quot; label=&quot;Search&quot; value={searchTerm} onChange={value =&gt; searchTerm.set(value)} /&gt;<br>    &lt;/Row&gt;<br>    &lt;SelectionGroup options={[&quot;All&quot;, &quot;To do&quot;, &quot;Done&quot;]} value={doneFilter} onChange={value =&gt; doneFilter.set(value)} /&gt;<br>  &lt;/Row&gt;<br>)</pre><p>To learn more about the layout components and their properties, please check <a href="https://gist.github.com/Tiagoperes/694516d05bf989cb0a222dd03c8f4537">this link</a>.</p><p>Now that we declared the states and header, we can use them in the return value of the function:</p><pre>return (<br>  &lt;ScreenComponent safeAreaTopBackground=&quot;#5F72C0&quot; statusBarColorScheme=&quot;dark&quot;&gt;<br>    &lt;Lifecycle onInit={loadItems} state={[isLoading, notes, searchTerm, doneFilter]}&gt;<br>      &lt;If condition={isLoading}&gt;<br>        &lt;Then&gt;&lt;Text&gt;Loading&lt;/Text&gt;&lt;/Then&gt;<br>        &lt;Else&gt;<br>          &lt;Column height=&quot;expand&quot; width=&quot;expand&quot; backgroundColor=&quot;#F1F3F5&quot;&gt;<br>            {header}<br>            &lt;ForEach items={notes} key=&quot;date&quot;&gt;<br>              {(section) =&gt; (<br>                &lt;Column marginTop={5}&gt;<br>                  &lt;Text weight=&quot;bold&quot;&gt;{section.get(&#39;date&#39;)}&lt;/Text&gt;<br>                  &lt;ForEach items={section.get(&#39;items&#39;)} key=&quot;id&quot;&gt;<br>                    {(item) =&gt; &lt;Text&gt;{item.get(&#39;title&#39;)}&lt;/Text&gt;}<br>                  &lt;/ForEach&gt;<br>                &lt;/Column&gt;<br>              )}<br>            &lt;/ForEach&gt;<br>          &lt;/Column&gt;<br>        &lt;/Else&gt;<br>      &lt;/If&gt;<br>    &lt;/Lifecycle&gt;<br>  &lt;/ScreenComponent&gt;<br>)</pre><p>Notice that, besides adding the header and states, we’ve also wrapped our content in a ScreenComponent and added some style to the first column under the component Else.</p><p>Save the backend files and run the client apps. They should now show the header you just created.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KPk9GEWmfTnovov2gi1P7g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xjuYZZ6O-sBg5anD4FPEow.png" /><figcaption>iOS result on the left. Android result on the right.</figcaption></figure><p>If you want to check the JSON version of the backend for this screen, please, visit <a href="https://gist.github.com/Tiagoperes/268bfbcf502ec31189ece7dfe66a6d1a#file-todoapp-list-json">this link</a>.</p><h3>Creating the UI for Each To Do Note</h3><p>Let’s now transform this ugly list into something nice to look at!</p><p>Each note must look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BSvBLJy8-UuMPI23KiDYTQ.png" /></figure><p>This is a row with three elements vertically centered:</p><ul><li>A circle indicates whether the note is done or not. If the note is done, it should be filled with a background. Otherwise, it should only have a border. Clicking the circle toggles the note status.</li><li>A column with two texts: the title and the note&#39;s description. This column expands in the horizontal axis to fill the space left after the other two elements are placed.</li><li>A red icon with a trash bin.</li></ul><p>Instead of writing this UI directly in todo-list.tsx, let’s create a new JSX Element (<a href="https://github.com/ZupIT/nimbus-docs/blob/main/backend-ts/composite-components.md">composite component</a>) called NoteCard. We are not required to separate this component from the rest of the code, but since this is a very well-defined piece of the UI, we&#39;ll use it to demonstrate how to compose multiple JSX components into a single one, making the code easier to read and reuse. This is not a new server-driven component, it&#39;s just a composition of the server-driven components we already have. For this reason, let&#39;s place it under a new directory called fragments.</p><p>fragments/NoteCard.tsx</p><pre>import { NimbusJSX, FC, State, condition, not, If, Then, isEmpty, Actions } from &#39;@zup-it/nimbus-backend-core&#39;<br>import { Column, Row, Text, Touchable } from &#39;@zup-it/nimbus-backend-layout&#39;<br>import { Icon } from &#39;../components/Icon&#39;<br>import { Note } from &#39;../types&#39;<br><br>interface Props {<br>  value: State&lt;Note&gt;,<br>}<br><br>export const NoteCard: FC&lt;Props&gt; = ({ value }) =&gt; (<br>  &lt;Row crossAxisAlignment=&quot;center&quot; paddingVertical={12} paddingHorizontal={20} backgroundColor=&quot;#FFFFFF&quot; minHeight={60}&gt;<br>    &lt;Touchable onPress={value.get(&#39;isDone&#39;).set(not(value.get(&#39;isDone&#39;)))}&gt;<br>      &lt;Column<br>        borderColor={condition(value.get(&#39;isDone&#39;), &#39;#5F7260&#39;, &#39;#E0E4E9&#39;)}<br>        backgroundColor={condition(value.get(&#39;isDone&#39;), &#39;#CDD3EB&#39;, &#39;#FFFFFF&#39;)}<br>        borderWidth={2}<br>        cornerRadius={14}<br>        width={22}<br>        height={22}<br>      /&gt;<br>    &lt;/Touchable&gt;<br>    &lt;Column marginHorizontal={20} width=&quot;expand&quot;&gt;<br>      &lt;Text weight=&quot;bold&quot; color=&quot;#616B76&quot;&gt;{value.get(&#39;title&#39;)}&lt;/Text&gt;<br>      &lt;If condition={not(isEmpty(value.get(&#39;description&#39;)))}&gt;<br>        &lt;Then&gt;<br>          &lt;Column marginTop={8}&gt;&lt;Text color=&quot;#85919C&quot;&gt;{value.get(&#39;description&#39;)}&lt;/Text&gt;&lt;/Column&gt;<br>        &lt;/Then&gt;<br>      &lt;/If&gt;<br>    &lt;/Column&gt;<br>    &lt;Icon name=&quot;delete&quot; size={20} color=&quot;#F00000&quot; /&gt;<br>  &lt;/Row&gt;<br>)</pre><p>We declare a composite component just like any other component, but instead of using the tag component, we use components that we have previously defined.</p><p>In the code above, it is important to notice the use of Nimbus Operations. We used the operations not, condition, and isEmpty to create the toggle (done/undone) and to check if the note has a description or not. <a href="https://github.com/ZupIT/nimbus-docs/blob/main/specification/operation.md">Operations</a>, in Nimbus, are part of the Nimbus Script specification, and they&#39;re used to transform the value of a state.</p><p>Now that we created the UI for the NoteCard, we can replace the text with the Note&#39;s title on the screen for listing the notes:</p><pre>&lt;ForEach items={section.get(&#39;items&#39;)} key=&quot;id&quot;&gt;<br>  {(item) =&gt; &lt;NoteCard value={item} /&gt;}<br>&lt;/ForEach&gt;</pre><p>To run the app with these changes, reload the app so it can get the latest JSON from the backend.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DQ79E3dis7wmqczn4oQGMA.png" /></figure><p>We need something to separate one note from another. To do so, let&#39;s create another composite component that renders a grey line and use it between each list item.</p><p>fragments/separator.tsx</p><pre>import { NimbusJSX } from &quot;@zup-it/nimbus-backend-core&quot;<br>import { Column } from &quot;@zup-it/nimbus-backend-layout&quot;<br><br>export const Separator = () =&gt; &lt;Column height={1} width=&quot;expand&quot; backgroundColor=&quot;#E0E4E9&quot; /&gt;</pre><p>screens/todo-list.tsx</p><pre>&lt;Text weight=&quot;bold&quot;&gt;{section.get(&#39;date&#39;)}&lt;/Text&gt;<br>&lt;Separator /&gt;<br>&lt;ForEach items={section.get(&#39;items&#39;)} key=&quot;id&quot;&gt;<br>  {(item) =&gt; (<br>    &lt;&gt;<br>      &lt;NoteCard value={item} /&gt;<br>      &lt;Separator /&gt;<br>    &lt;/&gt;<br>  )}<br>&lt;/ForEach&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k7DltVdpeVrWcWc8-CXW3Q.png" /></figure><p>Much better!</p><p>Now that the notes occupy a much larger vertical space, we should add a ScrollView to make the content scrollable:</p><pre>&lt;Column height=&quot;expand&quot; width=&quot;expand&quot; backgroundColor=&quot;#F1F3F5&quot;&gt;<br>  {header}<br>  &lt;ScrollView&gt;<br>    &lt;ForEach items={notes} key=&quot;date&quot;&gt;<br>      { /* ... */ }<br>    &lt;/ForEach&gt;<br>  &lt;/ScrollView&gt;<br>&lt;/Column&gt;</pre><p>The only problem now is the date; it should be formatted into something readable.</p><h3>Formatting the Date</h3><p>To format the date, we need to use a custom operation. This operation must receive the date as a Long (Unix Timestamp in milliseconds) and return it as a String. We will use the format dd/MM/yyyy as the string representation for the date.</p><p>The contract for the custom operation is formatDate(Long): String, i.e., it&#39;s named formatDate, receives a Long as a parameter and returns a String.</p><h4><strong>Implementing formatDate on Android</strong></h4><p>Create the file formatDate.kt under a new package called operation:</p><pre>import br.com.zup.nimbus.annotation.AutoDeserialize<br>import java.text.SimpleDateFormat<br>import java.util.Date<br>import java.util.Locale<br>import java.util.TimeZone<br><br>const val DATE_FORMAT = &quot;dd/MM/yyyy&quot;<br><br>@AutoDeserialize<br>internal fun formatDate(dateInMilliseconds: Long): String {<br>    val formatter = SimpleDateFormat(DATE_FORMAT, Locale.ENGLISH)<br>    formatter.timeZone = TimeZone.getTimeZone(&quot;UTC&quot;)<br>    val dateTime = Date(dateInMilliseconds)<br>    return formatter.format(dateTime)<br>}</pre><p>To make the function formatDate available as an operation to Nimbus, we annotate it with @AutoDeserialize and register it to the UI Library:</p><p>Nimbus.kt</p><pre>private val todoAppUI = NimbusComposeUILibrary(&quot;todoapp&quot;)<br>    // ...<br>    .addOperation(&quot;formatDate&quot;) { formatDate(it) }</pre><p>The @AutoDeserialize annotation is responsible for generating the code called by the line above. For this reason, just like the components, this will be available only after the project is built.</p><h4><strong>Implementing formatDate on iOS</strong></h4><p>Create the file FormatDate.swift under a new directory called Operations.</p><pre>import Foundation<br>import NimbusSwiftUI<br><br>struct FormatDate: OperationDecodable {<br>  static var properties = [&quot;timeMillis&quot;]<br><br>  var timeMillis: Int<br><br>  func execute() -&gt; String? {<br>    let date = Date(timeIntervalSince1970: TimeInterval(timeMillis / 1000))<br>    let formatter = DateFormatter()<br>    formatter.dateFormat = &quot;dd/MM/yyyy&quot;<br>    formatter.timeZone = TimeZone(abbreviation: &quot;UTC&quot;)<br>    return formatter.string(from: date)<br>  }<br>}</pre><p>An operation is implemented on iOS with a struct that conforms to OperationDecodable. The required array properties must contain the identifiers for each parameter received by the operation, in order. The method, execute, is what actually runs when the operation is called by Nimbus. In this case, it must return a string.</p><p>Just like components, we need to register it to a UI Library:</p><p>ContentView.swift</p><pre>let todoAppUI = NimbusSwiftUILibrary(&quot;todoapp&quot;)<br>  // ...<br>  .addOperation(&quot;formatDate&quot;, FormatDate.self)</pre><h4><strong>Declaring formatDate for the backend</strong></h4><p>If you&#39;re using only JSON, you can just call the operation inside an expression. Example: @{formatDate(date)}. In the backend for Node, we need to declare this operation. For this, create the file format-date.ts under the new directory src/operations.</p><pre>import { Expression, Operation } from &quot;@zup-it/nimbus-backend-core&quot;<br><br>export const formatDate = (time: Expression&lt;number&gt;) =&gt;<br>  new Operation&lt;string&gt;(&#39;formatDate&#39;, [time])</pre><p>To declare an operation in the backend, we create a function that receives the parameters for the operation and returns an object of type Operation&lt;T&gt;, where T is the operation&#39;s return type. The constructor for Operation receives the name of the operation (1st) and its parameters in a list (2nd). When serializing the UI into JSON, an Operation is transformed into a string in the format @{operationName(param1, param2, …)}.</p><h4><strong>Using formatDate</strong></h4><p>Now we can just use formatDate whenever we need to display a Long as a Date string in the backend.</p><p>screens/todo-list.tsx</p><pre>&lt;Column paddingVertical={12} paddingHorizontal={20}&gt;<br>  &lt;Text size={16} color=&quot;#616B76&quot;&gt;{formatDate(section.get(&#39;date&#39;))}&lt;/Text&gt;<br>&lt;/Column&gt;</pre><p>Note that, in addition to formatting the date, we added some spacing for the text by wrapping it in a column. We also added some styling by setting a font size and a color. The dates should be formatted if you rerun the client app (as seen in the images below).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TxuEgdMndhBRrVqHZL6AwQ.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6h8iA90Jl1V2MScSEb8neQ.png" /><figcaption>Android result on the left. iOS result on the right.</figcaption></figure><h3>Checkpoint 2</h3><p>Cool! You just reached the second checkpoint! You can validate your code against <a href="https://github.com/Tiagoperes/nimbus-todo-app/tree/part2">this branch in GitHub</a>. Next, we&#39;ll create the filters and the modal to edit a To Do Note.</p><h3>The Search Filter</h3><p>We previously implemented the UI for the header, which includes the search bar and its state. Unfortunately, it doesn’t do anything yet. Let’s fix this!</p><p>The text we type into the TextInput component will always be reflected in the value of the state searchTerm. To filter the notes by this text, we can just apply some kind of filter using this state.</p><p>To create this filter, we simply use the component If to render the notes conditionally. If the note contains the value of searchTerm, it gets rendered. Otherwise, it doesn&#39;t.</p><p>First, let&#39;s create a function that receives both the note and the search term and decides whether it should be rendered. In screens/todo-list.tsx (backend), create a new function called shouldRender:</p><pre>function shouldRender(note: State&lt;Note&gt;, searchTerm: State&lt;string&gt;) {<br>  const lowerSearchTerm = lowercase(searchTerm)<br>  const lowerTitle = lowercase(note.get(&#39;title&#39;))<br>  const lowerDescription = lowercase(note.get(&#39;description&#39;))<br>  const titleMatches = contains(lowerTitle, lowerSearchTerm)<br>  const descriptionMatches = contains(lowerDescription, lowerSearchTerm)<br>  return or(titleMatches, descriptionMatches)<br>}</pre><p>This is a very easy-to-read function. All Operations(lowercase, contains, or) are shipped with Nimbus and can be imported from @zup-it/nimbus-backend-core. We first transform all strings to lowercase to make a case-insensitive comparison. We test both the title and the description because we want to find the search term in any of them.</p><p>Now we can use this function to verify if the note should be rendered or not:</p><pre>&lt;ForEach items={section.get(&#39;items&#39;)} key=&quot;id&quot;&gt;<br>  {(item) =&gt; (<br>    &lt;If condition={shouldRender(item, searchTerm)}&gt;<br>      &lt;NoteCard value={item} /&gt;<br>      &lt;Separator /&gt;<br>    &lt;/If&gt;<br>  )}<br>&lt;/ForEach&gt;</pre><p>Here, we just replaced the previous &lt;&gt; with the pair &lt;If&gt;&lt;Then&gt;. Since we don’t want to render anything if the condition is not met, we don&#39;t need an Else.</p><p>Reload your app. The search bar should be working now!</p><h3>The “All,” “To Do,” and “Done” Filters</h3><p>Another part that doesn’t do anything yet is the component SelectionGroup. It should show only tasks that are done when &quot;Done&quot; is selected and only tasks that are not done when &quot;To Do&quot; is selected. &quot;All&quot; is the default option and doesn&#39;t filter anything.</p><p>With the implementation of the search field in mind, it becomes quite clear what we need to do to make it work. The filter&#39;s value is at the state doneFilter, we just need to change the function shouldRender so it takes into account the new filter.</p><pre>function shouldRender(note: State&lt;Note&gt;, searchTerm: State&lt;string&gt;, doneFilter: State&lt;&#39;All&#39; | &#39;To do&#39; | &#39;Done&#39;&gt;) {<br>  const lowerSearchTerm = lowercase(searchTerm)<br>  const lowerTitle = lowercase(note.get(&#39;title&#39;))<br>  const lowerDescription = lowercase(note.get(&#39;description&#39;))<br>  const titleMatches = contains(lowerTitle, lowerSearchTerm)<br>  const descriptionMatches = contains(lowerDescription, lowerSearchTerm)<br>  const matchesText = or(titleMatches, descriptionMatches)<br>  const matchesDone = and(eq(doneFilter, &#39;Done&#39;), note.get(&#39;isDone&#39;))<br>  const matchesToDo = and(eq(doneFilter, &#39;To do&#39;), not(note.get(&#39;isDone&#39;)))<br>  const matchesDoneFilter = or(eq(doneFilter, &#39;All&#39;), matchesDone, matchesToDo)<br>  return and(matchesDoneFilter, matchesText)<br>}</pre><p>Don&#39;t forget to fix the call to shouldRender:</p><pre>&lt;If condition={shouldRender(item, searchTerm, doneFilter)}&gt;</pre><p>Now, the condition to render is also linked to the state doneFilter. If you reload the app, all filters will apply correctly.</p><h3>Opening a Modal To Edit a Note</h3><p>We need to be able to edit a note. For this, we must make the title and description of a NoteCard clickable. Once the note is clicked, a modal for editing should be opened.</p><p>First, let&#39;s create a new property in NoteCard: onShowEditModal. This property is of type Actions and represents the actions to run when the edit modal is supposed to appear.</p><p>fragments/NoteCard.tsx</p><pre>interface Props {<br>  value: State&lt;Note&gt;,<br>  onShowEditModal: Actions,<br>}<br><br>export const NoteCard: FC&lt;Props&gt; = ({ value, onShowEditModal }) =&gt; (<br>  { /* ... */ }<br>)</pre><p>Now, we must make it so. When the text in a note is clicked, it calls the actions in onShowEditModal. To do this, we wrap the text components in a Touchable.</p><pre>&lt;Column marginHorizontal={20} width=&quot;expand&quot;&gt;<br>  &lt;Touchable onPress={onShowEditModal}&gt;<br>    &lt;Text weight=&quot;bold&quot; color=&quot;#616B76&quot;&gt;{value.get(&#39;title&#39;)}&lt;/Text&gt;<br>    &lt;If condition={not(isEmpty(value.get(&#39;description&#39;)))}&gt;<br>      &lt;Then&gt;<br>        &lt;Column marginTop={8}&gt;&lt;Text color=&quot;#85919C&quot;&gt;{value.get(&#39;description&#39;)}&lt;/Text&gt;&lt;/Column&gt;<br>      &lt;/Then&gt;<br>    &lt;/If&gt;<br>  &lt;/Touchable&gt;<br>&lt;/Column&gt;</pre><p>The NoteCard is now ready to receive an action to run when the text is clicked.</p><p>In the end, we want to open a modal when the NoteCard is clicked. So, let&#39;s create the modal in the new file: screens/edit-note.tsx:</p><pre>import { NimbusJSX } from &#39;@zup-it/nimbus-backend-core&#39;<br>import { Screen, ScreenRequest } from &#39;@zup-it/nimbus-backend-express&#39;<br>import { Column, Text, Touchable } from &#39;@zup-it/nimbus-backend-layout&#39;<br>import { Note } from &#39;../types&#39;<br><br>interface EditNoteScreenRequest extends ScreenRequest {<br>  state: {<br>    note: Note,<br>  },<br>}<br><br>export const EditNote: Screen&lt;EditNoteScreenRequest&gt; = ({ getViewState, navigator }) =&gt; {<br>  const note = getViewState(&#39;note&#39;)<br><br>  return (<br>    &lt;Column width=&quot;expand&quot; height=&quot;expand&quot; backgroundColor=&quot;#F1F3F5&quot; mainAxisAlignment=&quot;center&quot; crossAxisAlignment=&quot;center&quot;&gt;<br>      &lt;Text color=&quot;#616B76&quot; size={18} weight=&quot;bold&quot;&gt;Editing &quot;{note.get(&#39;title&#39;)}&quot;&lt;/Text&gt;<br>      &lt;Touchable onPress={navigator.dismiss()}&gt;<br>        &lt;Text&gt;Cancel&lt;/Text&gt;<br>      &lt;/Touchable&gt;<br>    &lt;/Column&gt;<br>  )<br>}</pre><p>This is a very simple modal that prints the title of the note we are editing and a button to close the modal.</p><p>The edit screen accepts a state parameter. For this reason, we must correctly type it with generics. Once a screen accepts a state parameter, one can use the function getViewState to access it.</p><p>Besides creating the screen file, we must also register it in screens/index.tsx.</p><pre>import { RouteMap } from &#39;@zup-it/nimbus-backend-express&#39;<br>import { EditNote } from &#39;./edit-note&#39;<br>import { ToDoList } from &#39;./todo-list&#39;<br><br>export const routes: RouteMap = {<br>  &#39;&#39;: ToDoList,<br>  &#39;/edit-note&#39;: EditNote,<br>}</pre><p>Let&#39;s edit the ToDoList (screens/todo-list.tsx) screen to open the modal every time a note is clicked. First, we need to import the EditNote screen and inject the navigator.</p><pre>import { EditNote } from &#39;../screens/edit-note&#39;<br><br>export const ToDoList: Screen = ({ navigator }) =&gt; {<br>  // ...<br>}</pre><p>Now, in the call to NoteCard, we tell the component to navigate to EditNote on the event onShowEditModal.</p><pre>&lt;NoteCard value={item} onShowEditModal={navigator.present(EditNote, { state: { note: item } })} /&gt;</pre><p>There are two ways of navigating forward in Nimbus: present and push. The first opens the next view on top of the current, like a modal. The second replaces the current view with the next.</p><p>The first parameter of forward navigation will always be the screen, while the second is an options object. If the next screen expects one or more states, the values of these states must be informed.</p><p>If you restart the app, it will now open the modal when the text in a note is clicked.</p><h3>Creating the UI for the EditNote Screen</h3><p>This step is very similar to what we did when we built the main screen (ToDoList). Instead of explaining every step, I will focus on the differences between implementing the two screens.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ywgGcObklXRUO_ZTlyJyjQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GRSqT6_zy6iX0SGF-fNKJQ.jpeg" /><figcaption>EditNote screen on iOS (left) and Android (right).</figcaption></figure><p>The screen is composed of the custom components:</p><p><strong>textInput</strong></p><p><strong>datePicker (new)</strong></p><ul><li>value: a long with the input&#39;s current value in Unix time format (milliseconds, UTC).</li><li>onChange: an event, i.e., a property that must receive a list of Nimbus Actions, which will be run once the event is triggered. This event is always triggered with the current value as a parameter.</li></ul><p><strong>button (new)</strong></p><ul><li>text: a string with the text that goes inside the button.</li><li>primary: an optional boolean that tells if this button is the most important on the screen.</li><li>onPress: an event, i.e., a property that must receive a list of Nimbus Actions, which will be run once the event is triggered.</li></ul><p>The textInput, although not new, is very different than the one we already have. It has different margins and also a label on iOS. There are two approaches to solve this problem, and both are correct:</p><ol><li>Create two textInput components, one for the search field and another for forms.</li><li>Create some properties in the textInput to allow its style to attend both scenarios.</li></ol><p>We chose the second option in this project and created a new boolean property called header.</p><p>Besides editing the textInput with the new option, we must create and register the component’s datePicker and button.</p><p>We won&#39;t go into the details on implementing any of these components because they&#39;re all analogous to everything we’ve done for the components in the first screen. Here are the source codes so you can copy and paste them into your project:</p><p><strong>Android</strong></p><ul><li><a href="https://github.com/Tiagoperes/nimbus-todo-app/blob/part3/android/app/src/main/java/com/todoapp/component/TextInput.kt">component/TextInput.kt</a></li><li><a href="https://github.com/Tiagoperes/nimbus-todo-app/blob/part3/android/app/src/main/java/com/todoapp/component/DatePicker.kt">component/DatePicker.kt</a></li><li><a href="https://github.com/Tiagoperes/nimbus-todo-app/blob/part3/android/app/src/main/java/com/todoapp/component/Button.kt">component/Button.kt</a></li><li><a href="https://github.com/Tiagoperes/nimbus-todo-app/blob/part3/android/app/src/main/java/com/todoapp/Nimbus.kt">Nimbus.kt</a></li></ul><p><strong>iOS</strong></p><ul><li><a href="https://github.com/Tiagoperes/nimbus-todo-app/blob/part3/ios/To%20Do%20App/Components/TextInput.swift">Components/TextInput.swift</a></li><li><a href="https://github.com/Tiagoperes/nimbus-todo-app/blob/part3/ios/To%20Do%20App/Components/DatePicker.swift">Components/DatePicker.swift</a></li><li><a href="https://github.com/Tiagoperes/nimbus-todo-app/blob/part3/ios/To%20Do%20App/Components/Button.swift">Components/Button.swift</a></li><li><a href="https://github.com/Tiagoperes/nimbus-todo-app/blob/part3/ios/To%20Do%20App/ContentView.swift">ContentView.swift</a></li></ul><p><strong>Backend</strong></p><ul><li><a href="https://github.com/Tiagoperes/nimbus-todo-app/blob/part3/backend/src/components/TextInput.tsx">components/TextInput.tsx</a></li><li><a href="https://github.com/Tiagoperes/nimbus-todo-app/blob/part3/backend/src/components/DatePicker.tsx">components/DatePicker.tsx</a></li><li><a href="https://github.com/Tiagoperes/nimbus-todo-app/blob/part3/backend/src/components/Button.tsx">components/Button.tsx</a></li><li><a href="https://github.com/Tiagoperes/nimbus-todo-app/blob/part3/backend/src/screens/todo-list.tsx">screens/todo-list.tsx</a> (textInput now uses the property header)</li></ul><p>Once we have all custom components implemented, we need to write the code for the screen.</p><p>screens/edit-note.tsx</p><pre>import { createState, NimbusJSX } from &#39;@zup-it/nimbus-backend-core&#39;<br>import { Screen, ScreenRequest } from &#39;@zup-it/nimbus-backend-express&#39;<br>import { Column, Row, Text } from &#39;@zup-it/nimbus-backend-layout&#39;<br>import { DatePicker } from &#39;../components/DatePicker&#39;<br>import { Button } from &#39;../components/Button&#39;<br>import { TextInput } from &#39;../components/TextInput&#39;<br>import { Note } from &#39;../types&#39;<br><br>interface EditNoteScreenRequest extends ScreenRequest {<br>  state: {<br>    note: Note,<br>  }<br>}<br><br>export const EditNote: Screen&lt;EditNoteScreenRequest&gt; = ({ getViewState, navigator }) =&gt; {<br>  const note = getViewState(&#39;note&#39;)<br>  const title = createState(&#39;title&#39;, note.get(&#39;title&#39;))<br>  const description = createState(&#39;description&#39;, note.get(&#39;description&#39;))<br>  const date = createState(&#39;date&#39;, note.get(&#39;date&#39;))<br><br>  return (<br>    &lt;Column state={[title, description, date]} width=&quot;expand&quot; height=&quot;expand&quot; backgroundColor=&quot;#F1F3F5&quot; mainAxisAlignment=&quot;center&quot; crossAxisAlignment=&quot;center&quot;&gt;<br>      &lt;Text color=&quot;#616B76&quot; size={18} weight=&quot;bold&quot;&gt;Editing note&lt;/Text&gt;<br>      &lt;Column margin={30} padding={20} backgroundColor=&quot;#FFFFFF&quot; borderColor=&quot;#E0E4E9&quot; borderWidth={1} cornerRadius={8}&gt;<br>        &lt;TextInput label=&quot;Title&quot; value={title} onChange={value =&gt; title.set(value)} /&gt;<br>        &lt;Column marginVertical={10}&gt;<br>          &lt;TextInput label=&quot;Description&quot; value={description} onChange={value =&gt; description.set(value)} /&gt;<br>        &lt;/Column&gt;<br>        &lt;DatePicker label=&quot;Date&quot; value={date} onChange={(newValue) =&gt; date.set(newValue)} /&gt;<br>        &lt;Row marginTop={20} width=&quot;expand&quot; mainAxisAlignment=&quot;center&quot;&gt;<br>          &lt;Column marginEnd={20}&gt;<br>            &lt;Button onPress={navigator.dismiss()}&gt;Cancel&lt;/Button&gt;<br>          &lt;/Column&gt;<br>          &lt;Button primary onPress={navigator.dismiss()}&gt;<br>            Save<br>          &lt;/Button&gt;<br>        &lt;/Row&gt;<br>      &lt;/Column&gt;<br>    &lt;/Column&gt;<br>  )<br>}</pre><p>The most important part of this code are the states and what we do with them. We declare three different states, one for each field in the form, and initialize them with their respective values in the note received as parameter. We then link each state to a form element using the properties value and onChange. This way, when interacting with the form, we don&#39;t directly alter the note. So if we press &quot;cancel,&quot; no change is persisted.</p><p>Both buttons do the same thing: they dismiss the modal. There are two ways of performing back navigation in Nimbus: dismiss() dismisses the modal view while pop() removes the last screen added to the stack via push(screen).</p><h3>The UI for Creating a New Note</h3><p>First, let&#39;s add a floating button with a plus icon on the bottom right corner of the ToDoList screen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q0K-cvejWbykjOb1HJNilA.png" /><figcaption>Screenshot of the button to create a new note</figcaption></figure><p>We&#39;ve already created this component in the last part of the tutorial: it&#39;s called circularButton. To place it in this stacked position, we must use the layout components &quot;stack&quot; and &quot;positioned&quot;. The stack will contain the header and the body as the background layer and the circular button as the foreground layer, positioned at the bottom right. See the code below:</p><p>screens/todo-list.tsx</p><pre>&lt;Stack height=&quot;expand&quot; width=&quot;expand&quot; backgroundColor=&quot;#F1F3F5&quot;&gt;<br>  &lt;Positioned&gt;<br>    {header}<br>    {body}<br>  &lt;/Positioned&gt;<br>  &lt;Positioned alignment=&quot;bottomEnd&quot; margin={28}&gt;<br>    &lt;CircularButton<br>      icon=&quot;plus&quot;<br>      onPress={navigator.present(EditNote, { state: { note: emptyNote() } })}<br>    /&gt;<br>  &lt;/Positioned&gt;<br>&lt;/Stack&gt;</pre><p>We replaced a Column with the pair Stack-Positioned and added the CircularButton. We also moved the whole body of the screen to a new variable called body.</p><p>We can reuse the modal to edit a note to implement the &quot;create a note&quot; feature. The only difference is that instead of passing an existing note to the modal, we&#39;ll create a new one. The implementation of emptyNote() is as follows:</p><pre>function emptyNote(): Note {<br>  return {<br>    id: 0,<br>    date: new Date().setUTCHours(0, 0, 0, 0),<br>    title: &#39;&#39;,<br>    description: &#39;&#39;,<br>    isDone: false,<br>  }<br>}</pre><p>If you rerun the app, there should be a new button to create a note, and it should open the EditNote screen with an empty form.</p><h3>Checkpoint 3</h3><p>You&#39;ve just reached the third checkpoint! You can check your progress with the source code <a href="https://github.com/Tiagoperes/nimbus-todo-app/tree/part3">here</a>. Next, we&#39;ll connect our UI with the REST API.</p><h3>The To-Do Note API</h3><p>Before connecting the app to the API, let&#39;s get to know it!</p><ul><li>POST /notes/auth: creates a unique key so you can start using the API. It also bootstraps the list of notes with the example we&#39;ve been using so far. Every other endpoint in this API requires the key returned in the body of this request to be passed as the value of the header key.</li><li>GET /notes: lists all notes grouped by date (NoteSection). The Note Sections are ordered by date (descending). We&#39;ll use this to replace the <a href="https://gist.githubusercontent.com/Tiagoperes/3888902b98494708202fa05569444451/raw/dbc705192e2f87233da2f1eec35936aef8125545/todo.json">gist file (JSON) we&#39;ve been using</a>.</li><li>PUT /notes: updates the note passed in the request&#39;s body (JSON). The response&#39;s body is the same as GET /notes, but updated.</li><li>POST /notes: creates the note passed in the request&#39;s body (JSON). The response&#39;s body is the same as GET /notes, but updated.</li><li>DELETE /notes/{id}: removes the note with the id informed in the route. The body of the response is the same as GET /notes, but updated.</li></ul><p>Important: this API should only be used for testing purposes. The notes are not encrypted and can be wiped at any time.</p><p>The API is located at &quot;<a href="https://beagle-playground.continuousplatform.com/notes/">https://beagle-playground.continuousplatform.com/notes</a>.&quot; Let’s first use a Rest Client or the terminal to create a key. Here&#39;s the cURL you need:</p><pre>curl --request POST \<br>  --url https://beagle-playground.continuousplatform.com/notes/auth</pre><p>Now, copy the key returned in the response and save it somewhere you can recover later.</p><pre>{<br> &quot;key&quot;: &quot;copy the value of this string&quot;<br>}</pre><h3>Listing the Notes in the App via the API</h3><p>First, we need a safe way to store our API key in the backend project. For this, we&#39;ll use the dependency <a href="https://www.npmjs.com/package/dotenv">dotenv</a>. In a terminal window, go to the directory of your backend project and install it.</p><pre>yarn add dotenv</pre><p>Open the file src/index.ts, import dotenv, and call dotenv.config().</p><pre>import * as dotenv from &#39;dotenv&#39;<br><br>dotenv.config()</pre><p>Now, let&#39;s create our env file in the root directory. It must be called &quot;.env&quot; and have the following content:</p><pre>TODO_API_KEY=&quot;the key you copied in the last section&quot;</pre><p>A .env file should never be published. Your .gitignore file is already set up to ignore it, so there is no need to worry.</p><p>Open the file src/constants.ts and add the following code to it:</p><pre>export const todoAPIUrl = &#39;https://beagle-playground.continuousplatform.com/notes&#39;<br>export const todoAPIKey = () =&gt; process.env.TODO_API_KEY ?? &#39;&#39;</pre><p>todoAPIKey is a function that gets the value specified for the variable TODO_API_KEY in the .env file.</p><p>Now, let&#39;s replace the request to GitHub with a request to our API. Open the file src/screens/todo-list.tsx and edit the properties url and headers of the action sendRequest:</p><pre>import { todoAPIKey, todoAPIUrl } from &#39;../constants&#39;<br><br>// ...<br><br>const loadItems = sendRequest&lt;NoteSection[]&gt;({<br>  url: todoAPIUrl,<br>  headers: { key: todoAPIKey() },<br>  onSuccess: response =&gt; notes.set(response.get(&#39;data&#39;)),<br>  onError: response =&gt; log({ level: &#39;error&#39;, message: response.get(&#39;message&#39;) }),<br>  onFinish: isLoading.set(false),<br>})</pre><p>If your server was already running, you must restart it.</p><p>Rerun the client app. It should work just like before, but it&#39;s now accessing a real API!</p><h3>Editing a Note</h3><p>Although we have the UI for editing a to-do note, it doesn’t work yet. We have to make it so that when the user presses the &quot;save&quot; button, a request is made to the API to update it. Moreover, we need to update the list of notes on the screen behind the modal and then close the modal.</p><p>Since the request to update a to-do note also returns the updated list of notes, we can use its response to update the UI.</p><p>In summary, here&#39;s the dynamic between the main screen (note list) and the edit modal:</p><ul><li>The main screen navigates to the modal, passing the note that must be edited as a state parameter.</li><li>The edit screen presents a form capable of editing the note&#39;s title, description, and date.</li><li>When the user saves the edited note, a request is made to the API.</li><li>The response to the request must be returned to the main screen, which must use to update the list.</li></ul><p>This is a two-way communication between the screens. The first part (main screen to modal) is already implemented via state parameters. For the second part, we&#39;ll use a feature of Nimbus Navigation called &quot;Screen events.&quot; While state parameters on navigation allow communication from the source screen to the target screen, screen events allow communication in the opposite direction.</p><p>A Screen event is an event that can be triggered by the next screen, and just like any event, it accepts Nimbus Actions.</p><p>Open the file screens/edit-note.tsx, and let&#39;s edit the screen&#39;s interface by adding a new event:</p><pre>interface EditNoteScreenRequest extends ScreenRequest {<br>  state: {<br>    note: Note,<br>  },<br>  events: {<br>    onSaveNote: NoteSection[],<br>  }<br>}</pre><p>This means the screen EditNote can trigger the event onSaveNote. It also means the event onSaveNote receives a parameter of type NoteSection[], i.e., the updated list of notes.</p><p>The idea is to, when the request to save a note succeeds, trigger the screen event onSaveNote with the response of the request. Let&#39;s implement this!</p><p>First, add some imports to edit-note.tsx:</p><pre>import { log, sendRequest } from &#39;@zup-it/nimbus-backend-core/actions&#39;<br>import { Note, NoteSection } from &#39;../types&#39;<br>import { todoAPIKey, todoAPIUrl } from &#39;../constants&#39;</pre><p>Now, inject the function triggerViewEvent into the screen:</p><pre>export const EditNote: Screen&lt;EditNoteScreenRequest&gt; = ({ getViewState, navigator, triggerViewEvent }) =&gt; {<br>  // ...<br>}</pre><p>Create the action to save a note, i.e., to send the request and trigger onSaveNote once it succeeds.</p><pre>const save = sendRequest&lt;NoteSection[]&gt;({<br>  url: todoAPIUrl,<br>  method: &#39;Put&#39;,<br>  headers: { key: todoAPIKey() },<br>  data: { id: note.get(&#39;id&#39;), title, description, date, isDone: note.get(&#39;isDone&#39;) },<br>  onSuccess: (response) =&gt; [<br>    triggerViewEvent(&#39;onSaveNote&#39;, response.get(&#39;data&#39;)),<br>    navigator.dismiss(),<br>  ],<br>  onError: (error) =&gt; log({ level: &#39;error&#39;, message: error.get(&#39;message&#39;) }),<br>})</pre><p>Just like we used sendRequest before to fetch the notes, we use it here to save a note. In data, we pass the request body, which consists of the data of the note we’re editing. Since id and isDone can&#39;t be edited through the form; we get their original value. All other values we get from the states are linked to the form. When the request fails, we log the error message. When the request succeeds, we trigger the screen event onSaveNote with the response body of the request, i.e., the list of notes after the update. We also dismiss the modal on successful requests.</p><p>Now, make the modal&#39;s primary button call the action we just created:</p><pre>&lt;Button primary onPress={save}&gt;Save&lt;/Button&gt;</pre><p>Open screens/todo-list.tsx to make the navigation to EditNote respond to the new event onSaveNote.</p><pre>&lt;NoteCard<br>  value={item}<br>  onShowEditModal={navigator.present(EditNote, { <br>    state: { note: item },<br>    events: { onSaveNote: updatedNotes =&gt; notes.set(updatedNotes) },<br>  })}<br>/&gt;</pre><p>We used the event parameter to update the state <em>notes</em>, which rerenders the list of notes with the newest value.</p><p>If you reload the client app now, the edit note feature will work as intended! It&#39;s nice to notice that we&#39;ve made no changes to the Android and iOS apps!</p><h3>Removing a Note</h3><p>Open the NoteCard component (fragments/NoteCard.tsx). Add a new event property called onRemove:</p><pre>interface Props {<br>  value: State&lt;Note&gt;,<br>  onShowEditModal: Actions,<br>  onRemove: Actions,<br>}<br><br>export const NoteCard: FC&lt;Props&gt; = ({ value, onShowEditModal, onRemove }) =&gt; (<br>  // ...<br>)</pre><p>Make the remove icon call this event when clicked:</p><pre>&lt;Touchable onPress={onRemove}&gt;<br>  &lt;Icon name=&quot;delete&quot; size={20} color=&quot;#F00000&quot; /&gt;<br>&lt;/Touchable&gt;</pre><p>Open the ToDoList screen (screens/todo-list.tsx) and create the action to remove a note by calling the API:</p><pre>const removeNote = (id: Expression&lt;number&gt;) =&gt; sendRequest&lt;NoteSection[]&gt;({<br>  url: `${todoAPIUrl}/${id}`,<br>  method: &#39;Delete&#39;,<br>  headers: { key: todoAPIKey() },<br>  onSuccess: response =&gt; notes.set(response.get(&#39;data&#39;)),<br>  onError: response =&gt; log({ level: &#39;error&#39;, message: response.get(&#39;message&#39;) }),<br>})</pre><p>Considering this action depends on the id of the note we want to delete, we created a function that returns an action instead of creating the action directly.</p><p>Now, use the new property on NoteCard (onRemove) to call this action:</p><pre>&lt;NoteCard<br>  value={item}<br>  onRemove={removeNote(item.get(&#39;id&#39;))}<br>  onShowEditModal={navigator.present(EditNote, {<br>    state: { note: item },<br>    events: { onSaveNote: updatedNotes =&gt; notes.set(updatedNotes) },<br>  })}<br>/&gt;</pre><p>Reload the client app. The remove feature should now be working!</p><h3>Checkpoint 4</h3><p>Congratulations, you made it to the final checkpoint! Use <a href="https://github.com/Tiagoperes/nimbus-todo-app/tree/part4">this code base</a> to verify your progress.</p><h3>Other Features</h3><p>Creating a note is analogous to editing a note while persisting its &quot;done/undone&quot; status is similar to removing it. I leave both as exercises for the reader.</p><p>Other good exercises to enhance the experience of the app are:</p><ul><li>Replace the text &quot;loading&quot; when loading the list of notes with a graphical indicator, like a spinner.</li><li>Show floating error messages when a request fails.</li></ul><p>These exercises can be implemented with what we&#39;ve learned throughout this tutorial.</p><p>The <a href="https://github.com/Tiagoperes/nimbus-todo-app/tree/main">main branch of the repository for this tutorial</a> contains these features implemented if you want to check them out.</p><p>We’ve finally completed the To Do app! As you’ve seen, most of the work for the application lies on the backend, while in the frontend, all we do is declare our components, actions, and operations.</p><p>I hope you enjoyed this first step of working with Nimbus. Nimbus is an open source project, and we’d love your feedback! Please, feel free to open new issues in <a href="https://github.com/ZupIT/nimbus-core">our repository</a> and help us with our backlog!</p><h3>Acknowledgements</h3><p>I’d like to thank Daniel Tes, <a href="https://medium.com/u/145eac7b0ece">Hernand Dos Santos Azevedo</a> and <a href="https://medium.com/u/23e790239a89">Arthur Bleil</a>. They are all developers of Nimbus SDUI, and they gave me a lot of help on build this sample app.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8b1102ab71d5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/building-server-driven-mobile-apps-with-nimbus-sdui-8b1102ab71d5">Building Server-Driven Mobile Apps With Nimbus SDUI</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building an application with Nimbus SDUI — Part 4 (final)]]></title>
            <link>https://medium.com/@tiagoperesfr/building-an-application-with-nimbus-sdui-part-4-final-c1f999d5d180?source=rss-23b2489b87ba------2</link>
            <guid isPermaLink="false">https://medium.com/p/c1f999d5d180</guid>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[server-driven-ui]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <dc:creator><![CDATA[Tiago Peres França]]></dc:creator>
            <pubDate>Tue, 14 Mar 2023 12:41:47 GMT</pubDate>
            <atom:updated>2023-03-20T12:22:14.237Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building an application with Nimbus SDUI — Part 4 (final)</h3><p>This article has been republished by <a href="https://betterprogramming.pub/">Better Programming</a> and can be found <a href="https://betterprogramming.pub/building-server-driven-mobile-apps-with-nimbus-sdui-8b1102ab71d5#31ad">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c1f999d5d180" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building an application with Nimbus SDUI — Part 3]]></title>
            <link>https://medium.com/@tiagoperesfr/building-an-application-with-nimbus-sdui-part-3-e36d643819b5?source=rss-23b2489b87ba------2</link>
            <guid isPermaLink="false">https://medium.com/p/e36d643819b5</guid>
            <category><![CDATA[server-driven-ui]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[swiftui]]></category>
            <dc:creator><![CDATA[Tiago Peres França]]></dc:creator>
            <pubDate>Tue, 07 Mar 2023 11:06:10 GMT</pubDate>
            <atom:updated>2023-03-20T12:20:44.606Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building an application with Nimbus SDUI — Part 3</h3><p>This article has been republished by <a href="https://betterprogramming.pub/">Better Programming</a> and can be found <a href="https://betterprogramming.pub/building-server-driven-mobile-apps-with-nimbus-sdui-8b1102ab71d5#82b9">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e36d643819b5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building an application with Nimbus SDUI — Part 2]]></title>
            <link>https://medium.com/@tiagoperesfr/building-an-application-with-nimbus-sdui-part-2-f46eb1999425?source=rss-23b2489b87ba------2</link>
            <guid isPermaLink="false">https://medium.com/p/f46eb1999425</guid>
            <category><![CDATA[server-driven-ui]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <dc:creator><![CDATA[Tiago Peres França]]></dc:creator>
            <pubDate>Tue, 28 Feb 2023 12:27:56 GMT</pubDate>
            <atom:updated>2023-03-20T12:18:41.818Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building an application with Nimbus SDUI — Part 2</h3><p>This article has been republished by <a href="https://betterprogramming.pub/">Better Programming</a> and can be found <a href="https://betterprogramming.pub/building-server-driven-mobile-apps-with-nimbus-sdui-8b1102ab71d5#f588">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f46eb1999425" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building an application with Nimbus SDUI — Part 1]]></title>
            <link>https://medium.com/@tiagoperesfr/building-an-application-with-nimbus-sdui-part-1-f84cd3f5b9f0?source=rss-23b2489b87ba------2</link>
            <guid isPermaLink="false">https://medium.com/p/f84cd3f5b9f0</guid>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[server-driven-ui]]></category>
            <category><![CDATA[swiftui]]></category>
            <dc:creator><![CDATA[Tiago Peres França]]></dc:creator>
            <pubDate>Mon, 20 Feb 2023 12:25:40 GMT</pubDate>
            <atom:updated>2023-03-20T12:17:16.790Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building an application with Nimbus SDUI — Part 1</h3><p>This article has been republished by <a href="https://betterprogramming.pub/">Better Programming</a> and can be found <a href="https://betterprogramming.pub/building-server-driven-mobile-apps-with-nimbus-sdui-8b1102ab71d5">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f84cd3f5b9f0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Announcing Nimbus Server-Driven UI Beta]]></title>
            <link>https://medium.com/better-programming/announcing-nimbus-server-driven-ui-beta-9a0d95686fd9?source=rss-23b2489b87ba------2</link>
            <guid isPermaLink="false">https://medium.com/p/9a0d95686fd9</guid>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <dc:creator><![CDATA[Tiago Peres França]]></dc:creator>
            <pubDate>Sun, 12 Feb 2023 20:22:01 GMT</pubDate>
            <atom:updated>2023-02-20T12:29:26.773Z</atom:updated>
            <content:encoded><![CDATA[<h4>Easy-to-use libraries for building Jetpack Compose and SwiftUI applications driven by the backend</h4><figure><img alt="White clouds on a blue sky" src="https://cdn-images-1.medium.com/max/1024/0*GDx3J5yvVTOvZLF-" /><figcaption>Photo by <a href="https://unsplash.com/@billy_huy?utm_source=medium&amp;utm_medium=referral">Billy Huynh</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Server Driven UI (SDUI)</h3><p>SDUI is the ability to control the looks, the behavior and the flow of a frontend application via the backend. This is very useful for several reasons:</p><ol><li>It provides fast updates to the user since there’s no need to go through the Apple Store or the Play Store to alter the user interface (UI).</li><li>It allows the app owner to provide different UIs for different users via the backend.</li><li>The frontend applications still need to implement every component with a reference in the backend, but all the UI logic programmed in the backend (represented by a JSON) can be shared among the frontend applications, which reduces the total amount of code in the project and its maintenance.</li></ol><p>It is not the goal of this article to go into the details of SDUI as a concept. To know more about the subject, we recommend reading the articles below:</p><ul><li><a href="https://www.thoughtworks.com/radar/techniques/server-driven-ui"><em>https://www.thoughtworks.com/radar/techniques/server-driven-ui</em></a></li><li><a href="https://medium.com/airbnb-engineering/a-deep-dive-into-airbnbs-server-driven-ui-system-842244c5f5"><em>https://medium.com/airbnb-engineering/a-deep-dive-into-airbnbs-server-driven-ui-system-842244c5f5</em></a></li><li><a href="https://joebirch.co/android/server-driven-ui-part-1-the-concept/"><em>https://joebirch.co/android/server-driven-ui-part-1-the-concept/</em></a></li><li><a href="https://appmaster.io/blog/backend-driven-development-ios"><em>https://appmaster.io/blog/backend-driven-development-ios</em></a></li></ul><h3>Nimbus SDUI</h3><p>As of 2023, we have very stable versions of both Jetpack Compose and SwiftUI, which are frameworks that already work with the concept of components, states, and reactivity. Implementing Server Driven UI on top of them is a much cleaner approach than building it from Android Views or UIKit (the approach of all current open-source libraries for SDUI).</p><p>Furthermore, it’s much easier for a developer familiar with Compose and SwiftUI to understand how SDUI libraries behave since all of them work with states and reactivity.</p><p><em>Since Nimbus depends on Compose and SwiftUI, it requires Android Lollipop (5.1, API 21) and iOS 13.</em></p><p>Nimbus, for the frontend developer, was developed with the idea that, if Jetpack Compose (on Android) and SwiftUI (on iOS) are known, no further knowledge should be required to implement an application compatible with Server Driven Views. This is not an easy task to accomplish, but we can say that we got almost there!</p><p>For the frontend developer, it is very easy to start building apps with Nimbus, and the code for the components can be decoupled from the lib itself, which allows them to work for both native views and server-driven views. Let’s see some examples.</p><p>A Button component in Jetpack Compose:</p><pre>@Compose<br>fun MyButton(text: String, enabled: Boolean?, onPress: (() -&gt; Unit)) {<br>    Button(onClick = onPress, enabled = enabled != false) {<br>        Text(text)<br>    }<br>}</pre><p>A Button component that works for both native views and server-driven views:</p><pre>@Compose<br>@AutoDeserialize<br>fun MyButton(text: String, enabled: Boolean?, onPress: (() -&gt; Unit)) {<br>    Button(onClick = onPress, enabled = enabled != false) {<br>        Text(text)<br>    }<br>}</pre><p>That’s it! An annotation. Now the component is ready to be registered for server-driven usage!</p><p>Now let’s see the same button in SwiftUI:</p><pre>struct MyButton: View {<br>  var text: String<br>  var onPress: () -&gt; Void<br>  <br>  var body: some View {<br>    Button(text) {<br>      onPress()<br>    }<br>  }<br>}</pre><p>The button is ready for use on both native views and server-driven views:</p><pre>struct MyButton: View, Decodable {<br>  var text: String<br>  <br>  @Event<br>  var onPress: () -&gt; Void<br>  <br>  var body: some View {<br>    Button(text) {<br>      onPress()<br>    }<br>  }<br>}</pre><p>For Swift, we need an annotation (property wrapper) to tell Nimbus &quot;onPress&quot; should be treated as an event and protocol conformance: Decodable. These changes to the original component make no difference when the component is used natively but allow it to work with Nimbus.</p><p>Using the same logic, we can define the components &quot;Column&quot;, &quot;Text&quot; and &quot;TextInput&quot;.</p><p>On Android:</p><pre>@Composable<br>@AutoDeserialize<br>internal fun Column(content: @Composable () -&gt; Unit) {<br>    Column {<br>        content()<br>    }<br>}<br><br>@OptIn(ExperimentalUnitApi::class)<br>@Composable<br>@AutoDeserialize<br>internal fun MyText(text: String?, size: Float?) {<br>    Text(<br>        text = text ?: &quot;&quot;,<br>        fontSize = TextUnit((size ?: 12F), TextUnitType.Sp),<br>    )<br>}<br><br>@Composable<br>@AutoDeserialize<br>fun TextInput(<br>    label: String,<br>    value: String?,<br>    onChange: (value: String) -&gt; Unit,<br>) {<br>    TextField(<br>        value = value ?: &quot;&quot;,<br>        onValueChange = onChange,<br>        label = { Text(label) },<br>    )<br>}</pre><p>On iOS:</p><pre>struct Column&lt;Content: View&gt;: View, Decodable {<br>  @Children var children: () -&gt; Content<br>  <br>  var body: some View {<br>    VStack() {<br>      children()<br>    }<br>  }<br>}<br><br>struct MyText: View, Decodable {<br>  var text: String?<br>  var size: Double?<br>  <br>  var body: some View {<br>    Text(text ?? &quot;&quot;)<br>      .font(.system(size: size ?? 12.0))<br>  }<br>}<br><br>struct TextInput: View, Decodable {<br>  var label: String<br>  <br>  var value: String?<br>  @StatefulEvent var onChange: (String) -&gt; Void<br>  <br>  var body: some View {<br>    let binding = Binding(<br>        get: { value ?? &quot;&quot; },<br>        set: { onChange($0) }<br>    )<br>    <br>    TextField(label, text: binding)<br>  }<br>}</pre><p>As seen in the examples, we don’t need different components for native views and server-driven views, the fact that we are going to use Server Driven UI in our app, doesn’t make us develop any differently. Nimbus can update the values of the component&#39;s properties and interpret functions like &quot;onPress&quot; and &quot;onChange&quot; without any further interaction from the developer.</p><h3>The Backend (JSON)</h3><p>Given we have all the components implemented and registered (<a href="https://github.com/ZupIT/nimbus-docs/blob/main/compose/component.md#2-register-the-component-to-the-ui-library"><em>Android docs</em></a> | <a href="https://github.com/ZupIT/nimbus-docs/blob/main/swiftui/component.md#component-registration"><em>iOS docs</em></a>) in the front, it’s time to represent a view in the backend.</p><p>For the backend development, the learning curve is steeper, we are trying to make it minimal by making it as close as possible to Jetpack Compose, SwitfUI and React, but the developer will need to spend some time on the documentation to master it.</p><p>Just like most SDUI solutions, Nimbus uses a JSON to represent a view. Using the components previously implemented, we define a very simple application that requests the user name and age on the first page and, on the second page, presents a button to buy some bears as long as the age was equal to or greater than 18. Check the gif below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/380/1*03PtBFHCW7VZNVq1dplb_g.gif" /><figcaption>Example of the application we&#39;re going to explore</figcaption></figure><p>JSON for the first page:</p><pre>{<br>  &quot;_:component&quot;: &quot;sample:column&quot;,<br>  &quot;state&quot;: {<br>    &quot;name&quot;: &quot;&quot;,<br>    &quot;age&quot;: &quot;&quot;<br>  },<br>  &quot;children&quot;: [<br>    {<br>      &quot;_:component&quot;: &quot;sample:textInput&quot;,<br>      &quot;properties&quot;: {<br>        &quot;value&quot;: &quot;@{name}&quot;,<br>        &quot;label&quot;: &quot;Write your name&quot;,<br>        &quot;onChange&quot;: [<br>          {<br>            &quot;_:action&quot;: &quot;setState&quot;,<br>            &quot;properties&quot;: {<br>              &quot;path&quot;: &quot;name&quot;,<br>              &quot;value&quot;: &quot;@{onChange}&quot;<br>            }<br>          }<br>        ]<br>      }<br>    },<br>    {<br>      &quot;_:component&quot;: &quot;sample:textInput&quot;,<br>      &quot;properties&quot;: {<br>        &quot;value&quot;: &quot;@{age}&quot;,<br>        &quot;label&quot;: &quot;Write your age&quot;,<br>        &quot;onChange&quot;: [<br>          {<br>            &quot;_:action&quot;: &quot;setState&quot;,<br>            &quot;properties&quot;: {<br>              &quot;path&quot;: &quot;age&quot;,<br>              &quot;value&quot;: &quot;@{onChange}&quot;<br>            }<br>          }<br>        ]<br>      }<br>    },<br>    {<br>      &quot;_:component&quot;: &quot;sample:button&quot;,<br>      &quot;properties&quot;: {<br>        &quot;text&quot;: &quot;Next&quot;,<br>        &quot;onPress&quot;: [<br>          {<br>            &quot;_:action&quot;: &quot;push&quot;,<br>            &quot;properties&quot;: {<br>              &quot;url&quot;: &quot;/second&quot;,<br>              &quot;state&quot;: {<br>                &quot;name&quot;: &quot;@{name}&quot;,<br>                &quot;age&quot;: &quot;@{age}&quot;<br>              }<br>            }<br>          }<br>        ]<br>      }<br>    }<br>  ]<br>}</pre><p>JSON for the second page:</p><pre>{<br>  &quot;_:component&quot;: &quot;sample:column&quot;,<br>  &quot;state&quot;: {<br>    &quot;beers&quot;: 0<br>  },<br>  &quot;children&quot;: [<br>    {<br>      &quot;_:component&quot;: &quot;sample:text&quot;,<br>      &quot;properties&quot;: {<br>        &quot;text&quot;: &quot;@{name} has @{beers} bears.&quot;<br>      }<br>    },<br>    {<br>      &quot;_:component&quot;: &quot;sample:button&quot;,<br>      &quot;properties&quot;: {<br>        &quot;text&quot;: &quot;Buy 1 beer&quot;,<br>        &quot;onPress&quot;: [<br>          {<br>            &quot;_:action&quot;: &quot;condition&quot;,<br>            &quot;properties&quot;: {<br>              &quot;condition&quot;: &quot;@{gte(age, 18)}&quot;,<br>              &quot;onTrue&quot;: [<br>                {<br>                  &quot;_:action&quot;: &quot;setState&quot;,<br>                  &quot;properties&quot;: {<br>                    &quot;path&quot;: &quot;beers&quot;,<br>                    &quot;value&quot;: &quot;@{sum(beers, 1)}&quot;<br>                  }<br>                }<br>              ],<br>              &quot;onFalse&quot;: [<br>                {<br>                  &quot;_:action&quot;: &quot;log&quot;,<br>                  &quot;properties&quot;: {<br>                    &quot;message&quot;: &quot;@{name} must be at least 18 years old to drink.&quot;,<br>                    &quot;level&quot;: &quot;Error&quot;<br>                  }<br>                }<br>              ]<br>            }<br>          }<br>        ]<br>      }<br>    }<br>  ]<br>}</pre><p>Notice that by using the delimiters &quot;@{&quot; and &quot;}&quot; we can write some code to the JSON. This is the Nimbus Script. This script is a very basic programming language that allows complex behavior to be programmed in the backend, meaning that your server-driven views can be as dynamic as you wish without the need of making another request to the backend. This language is not yet final and will be extended to support more use cases before the final release of Nimbus. For details on it, we refer the reader to the <a href="https://github.com/ZupIT/nimbus-docs/blob/main/specification/expression.md">documentation</a>.</p><p>To make the view dynamic, in addition to the Nimbus Script, Nimbus uses States and Actions. States work similarly to any other framework for reactive UIs. The State is declared for a component and visible to itself and any descendent. When a state has its value changed, every component that depends on it is automatically updated (re-rendered).</p><p>Actions are functions in the frontend that implement a given behavior, e.g. <em>&quot;setState&quot;</em>: changes the value of a state; <em>&quot;log&quot;</em>: writes a message to the console; <em>&quot;push&quot;</em>: navigates to another page; <em>&quot;condition&quot;</em> decides between two actions to run based on a condition. Besides the default actions shipped with Nimbus, the developer can implement any custom action for the application.</p><h3>A backend tool for creating the JSONs</h3><p>Let&#39;s be honest, nobody likes to write raw JSONs. For this reason, Nimbus will have both a Typescript (Node.js) and a Kotlin backend library. Our focus right now is in the frontend, which is where most of the complexity lies. However, we have an alpha implementation of the Backend for Typescript that can already be used.</p><p>Let’s see the previous example in JSON using the Nimbus Backend TS lib:</p><p>First page:</p><pre>export const FirstPage: Screen = ({ navigator }) =&gt; {<br>  const name = createState(&#39;name&#39;, &#39;&#39;)<br>  const age = createState(&#39;age&#39;, &#39;&#39;)<br><br>  return (<br>    &lt;Column state={[name, age]}&gt;<br>      &lt;TextInput value={name} label=&quot;Write your name&quot; onChange={value =&gt; name.set(value)} /&gt;<br>      &lt;TextInput value={age} label=&quot;Write your age&quot; onChange={value =&gt; age.set(value)} /&gt;<br>      &lt;Button text=&quot;Next&quot; onPress={navigator.push(SecondPage, { state: { name, age }})} /&gt;<br>    &lt;/Column&gt;<br>  )<br>}</pre><p>Second page:</p><pre>interface SecondPageData extends ScreenRequest {<br>  state: {<br>    name: string,<br>    age: string,<br>  }<br>}<br><br>export const SecondPage: Screen&lt;SecondPageData&gt; = ({ getViewState }) =&gt; {<br>  const beers = createState(&#39;beers&#39;, 0)<br>  const name = getViewState(&#39;name&#39;)<br>  const age = getViewState(&#39;age&#39;)<br>  const buy = conditionalAction({<br>    condition: gte(age, 18),<br>    onTrue: beers.set(sum(beers, 1)),<br>    onFalse: log({ message: `${name} must be at least 18 years old to drink.`, level: &#39;Error&#39; })<br>  })<br><br>  return (<br>    &lt;Column state={beers}&gt;<br>      &lt;Text&gt;{name} has {beers} bears.&lt;/Text&gt;<br>      &lt;Button onPress={buy}&gt;Buy 1 beer&lt;/Button&gt;<br>    &lt;/Column&gt;<br>  )<br>}</pre><p>If you ever worked with React, you’ll notice that this is very similar!</p><p>We intend to start the development of a Kotlin version of the backend as soon as we have a stable version of the frontend libraries (1.0.0).</p><h3>Component libraries</h3><p>Nimbus, by itself, just enables SDUI in your project, it doesn’t have any UI component built in. However, we believe that the same layout components will be needed by most applications, thus, in addition to Nimbus, we also provide Nimbus Layout as a separate library. This tool brings to Nimbus components like: Column, Row, Stack, Positioned, Text, FlowRow, FlowColum, LazyRow, LazyColumn, among others.</p><p>Design System components like buttons, text inputs, toggles, and menus are not provided right now because they will probably differ from one application to another and it is best that each project implement its own. In the case of Design Systems already developed with SwiftUI or Compose, it suffices to expose them to Nimbus. Having said this, we might decide to implement a collection of them in the future to serve as a showcase.</p><h3>Current development stage</h3><p>We’re announcing Nimbus as it enters its first beta stage. Right now need some feedback. What can we do better? Which features are missing? What bugs haven’t been found yet?</p><p>The beta stage means that we’ll fix bugs and enhance the performance. We’ll also implement some minor features that are still missing. We&#39;ll still modify some parts of the API, but the changes will be minor.</p><h3>Useful links</h3><ul><li><a href="https://github.com/ZupIT/nimbus-docs"><strong>Documentation</strong></a>: the documentation for both the frontend and backend libraries. This is not in a website format yet, but you can read everything through GitHub.</li><li><a href="https://github.com/orgs/ZupIT/projects/26"><strong>Progress</strong></a>: current development progress of Nimbus.</li><li><a href="https://github.com/ZupIT/nimbus"><strong>Nimbus</strong></a>: the common code between Nimbus SwiftUI and Nimbus Compose. This has been built using Kotlin Multiplatform Mobile (KMM).</li><li><a href="https://github.com/ZupIT/nimbus-compose"><strong>Nimbus Compose</strong></a>: all modules necessary to run Nimbus in a Jetpack Compose project.</li><li><a href="https://github.com/ZupIT/nimbus-swiftui"><strong>Nimbus SwiftUI</strong></a>: all modules necessary to run Nimbus in a SwiftUI project.</li><li><a href="https://github.com/ZupIT/nimbus-layout-compose"><strong>Nimbus Compose Layout</strong></a>: layout components for Nimbus Compose.</li><li><a href="https://github.com/ZupIT/nimbus-layout-swiftui"><strong>Nimbus SwiftUI Layout</strong></a>: layout components for Nimbus SwiftUI.</li><li><a href="https://github.com/ZupIT/nimbus-backend-ts"><strong>Nimbus Backend TS</strong></a>: modules for the backend in Typescript.</li></ul><p>If you have a problem and don’t know where to post it, please use the <a href="https://github.com/ZupIT/nimbus">Nimbus Core repository.</a></p><h3>Up next</h3><p>In the next weeks, we&#39;ll be releasing a series of articles exploring how to create a simple To-Do App using Nimbus in both iOS and Android. Until then, you can read the <a href="https://github.com/ZupIT/nimbus-docs">documentation</a>.</p><p>Edit: the first part of the tutorial on how to create an app with Nimbus SDUI is now out! Click <a href="https://medium.com/@tiagoperesfr/building-an-application-with-nimbus-sdui-part-1-f84cd3f5b9f0">here</a> to read it.</p><h3>Conclusion</h3><p>Nimbus is a new set of libraries for creating applications with Server Driven UI in mind. As a design philosophy, Nimbus doesn’t require much additional knowledge to develop the front end and wants to be as less intrusive as possible in the application code by never coupling the SDUI logic with the component’s implementation.</p><p>On the backend, however, there will be a learning curve, but we want to minimize it by following the ideas of well-established libraries like Compose, SwiftUI, and React. It’s true that, if the backend developer doesn’t know any of these (which are frontend platforms), it might still be hard for them to declare a Server Driven View. In the end, even though the work has been shifted to the server, it is still, basically, a frontend task, and maybe, the best people to develop it would be frontend developers.</p><p>Nimbus takes advantage of both Compose and SwiftUI to provide a clean implementation of Server Driven UI. It is an open-source tool and can be used by any project that needs it (given they respect the minimum version requirements of iOS and Android).</p><p>Nimbus is in the Beta stage, it is not yet stable, we count on the community for testing it and giving us feedback.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9a0d95686fd9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/announcing-nimbus-server-driven-ui-beta-9a0d95686fd9">Announcing Nimbus Server-Driven UI Beta</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Gerenciamento fácil de requisições no react usando as bibliotecas @zup-next: Parte 1.]]></title>
            <link>https://medium.com/@tiagoperesfr/gerenciamento-f%C3%A1cil-de-requisi%C3%A7%C3%B5es-no-react-usando-as-bibliotecas-zup-next-parte-1-a13dba7ca446?source=rss-23b2489b87ba------2</link>
            <guid isPermaLink="false">https://medium.com/p/a13dba7ca446</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[redux-saga]]></category>
            <category><![CDATA[redux]]></category>
            <dc:creator><![CDATA[Tiago Peres França]]></dc:creator>
            <pubDate>Fri, 07 Jun 2019 17:54:39 GMT</pubDate>
            <atom:updated>2019-06-07T17:54:39.578Z</atom:updated>
            <content:encoded><![CDATA[<h3>Gerenciamento fácil de requisições no React usando as bibliotecas @zup-next: Parte 1.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WXor9852rKcMTTjEMiXGpw.png" /></figure><p><em>This article is also available in </em><a href="https://medium.com/@tiagoperesfr/request-management-made-easy-with-zup-next-libraries-for-react-part-1-b89dda8abac9"><em>english</em></a><em>.</em></p><h3>Motivação</h3><p>Nós, da Zup IT, geralmente usamos um conjunto de utilitários quando precisamos gerenciar requisições no React. Recentemente, decidimos compartilhar essas ferramentas através de dois repositórios: <a href="https://github.com/zup-next/redux-resource"><em>redux-resource</em></a> e <a href="https://github.com/zup-next/redux-action-cache"><em>redux-action-cache</em></a>. Neste artigo, falaremos sobre o primeiro, que é responsável por criar quase tudo que precisamos para controlar nossas requisições através das ações e estado do redux.</p><p>Sejamos sinceros, criar tipos de ações (constantes), <em>action creators</em>, <a href="https://redux.js.org/basics/reducers"><em>reducers</em></a> e <a href="https://redux-saga.js.org/">sagas</a> para todas as requisições é bem chato. Isso leva tempo e, às vezes, fica difícil de manter. Quando usamos serviços REST, todo GET, PUT, POST ou DELETE é basicamente a mesma coisa. Porque estamos recriando o código toda vez que precisamos chamar um novo serviço? E se também tratarmos nossas requisições como recursos REST no <em>front end</em>? Não poderíamos então usar o mesmo tratamento para todas as requisições e evitar repetição de código? É exatamente essa a intenção da nossa biblioteca <em>redux-resource</em>.</p><h3>Uma aplicação usando nossa biblioteca</h3><p>Este artigo apresenta uma aplicação simples criada com o <em>redux-resource</em>. A aplicação se trata de uma loja online de filmes que permite o usuário verificar seu saldo atual, ver o catálogo de filmes e fazer compras. O foco aqui é em como gerenciar as requisições, portanto não entraremos em detalhes quanto aos estilos ou outros componentes react.</p><p>O projeto demo com o código completo pode ser encontrado <a href="https://github.com/zup-next/react-demos/tree/master/demo-simple">aqui</a>. Você pode seguir as instruções no <em>readme </em>do projeto para executá-lo. As imagens a seguir ilustram o funcionamento da aplicação:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Am6M2Fndttf7fSj0mrxByA.png" /><figcaption>Tela 1: home</figcaption></figure><p>Na <em>Tela 1</em>, o usuário confere o saldo e o catálogo de filmes disponíveis para compra.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BAH8SQ__gmucHw2Y34zmFQ.png" /><figcaption>Tela 2: detalhes do filme</figcaption></figure><p>Na <em>Tela 2</em>, os detalhes do filme escolhido são apresentados.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q7ySNEOUeIR6zm3UMiE1sA.png" /><figcaption>Tela 3: pagamento</figcaption></figure><p>A <em>Tela 3</em> é responsável por efetuar o pagamento e finalizar a compra.</p><p>Na primeira parte desta série de três artigos, utilizaremos a <em>Tela 1</em> e a <em>Tela 2</em> para mostrar o uso básico da biblioteca. Na segunda parte, a<em> Tela 3</em> para que seja possível efetuar o pagamento de compras. Na terceira e última parte, trataremos o problema onde múltiplas requisições são disparadas para carregar um mesmo recurso no decorrer do ciclo de vida da aplicação, introduzindo a biblioteca <em>redux-action-cache.</em></p><h3>Escrevendo a aplicação</h3><p>A API REST que estamos utilizando para construir a aplicação consiste dos seguintes serviços:</p><ul><li><strong>GET /profile:</strong> recupera o perfil do usuário</li><li><strong>PUT /profile:</strong> atualiza o perfil do usuário de acordo com os dados passados no corpo da requisição</li><li><strong>GET /catalog:</strong> recupera a lista de filmes disponíveis</li><li><strong>GET /wallet:</strong> recupera a carteira do usuário. A carteira consiste de um objeto com duas propriedades: <em>balance</em> e <em>cards</em>. <em>“balance”</em> é um número representando o saldo e <em>“cards”</em> é a lista de cartões de crédito.</li><li><strong>POST /wallet:</strong> adiciona um novo cartão de crédito à carteira</li><li><strong>DELETE /wallet:</strong> remove um cartão de crédito da carteira</li><li><strong>POST /order:</strong> cria uma compra</li></ul><p>Atenção: apesar das requisições http serem GET, POST, PUT ou DELETE, as operações definidas no <em>redux-resource</em> são <em>load</em>, <em>create</em>, <em>update</em> e <em>remove</em>.</p><p>Podemos identificar três recursos ao analizar as duas primeiras telas: o perfil do usuário, o saldo (carteira) e o catálogo de filmes. A primeira coisa que precisamos fazer é criar as funções da API. Recomendamos usar a biblioteca <a href="https://github.com/axios/axios"><em>axios</em></a> para isso.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f7ac738f5f444535b5a3e86e2d5865e1/href">https://medium.com/media/f7ac738f5f444535b5a3e86e2d5865e1/href</a></iframe><p>Agora que definimos a interface da API, podemos criar os recursos:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ce14def3a53d6154423aa9f8bf87f16b/href">https://medium.com/media/ce14def3a53d6154423aa9f8bf87f16b/href</a></iframe><p>Simples assim! Todo recurso pode ter as operações <em>load</em>, <em>update</em>, <em>create</em> ou <em>remove</em>. Neste exemplo, usamos as operações <em>update profile</em>, <em>create wallet</em> e <em>remove wallet</em> apenas para ilustrar como elas poderiam ser usadas. De fato, não faremos chamadas a nenhuma delas no decorrer do código.</p><p>A função <em>createResource </em>retorna um objeto com as chaves:</p><ul><li><em>types</em>: os tipos das ações <em>(strings)</em></li><li><em>actions</em>: os <em>actions creators</em> (funções que criam ações)</li><li><em>reducers</em>: os <em>reducers</em> a serem providenciados ao redux</li><li><em>sagas</em>: as sagas a serem providenciadas ao <em>redux-saga</em></li></ul><p>Utilizamos o valor de retorno de <em>createResource</em> para criar nossa <em>store</em> e disparar ações. O código seguinte mostra como criar o <em>store</em> do redux com os recursos que criamos.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b3d33aa3db8b12de67ff53813727c641/href">https://medium.com/media/b3d33aa3db8b12de67ff53813727c641/href</a></iframe><p>Acima, <em>combineReducers </em>é uma função típica do redux, enquanto <em>createEffects </em>é uma função utilitária da nossa biblioteca responsável por criar os efeitos do <em>redux-saga</em>, ela recebe um objeto onde as chaves correspondem ao tipo das ações e os valores correspondem as funções <em>generator</em>. Para mais detalhes em relação à função <em>createEffects</em>, por favor leia <a href="https://github.com/zup-next/redux-resource#createeffectstypetosagamap-effect">nossa documentação</a>.</p><p>Agora que configuramos os recursos e o <em>store</em> do redux, podemos começar a usá-los! Nós dividimos a <em>Tela 1</em> e a <em>Tela 2</em> em três <em>containers</em>:</p><ul><li><strong>Header:</strong> responsável pelo cabeçalho, compartilhado por todas as telas</li><li><strong>Home:</strong> responsável pelo conteúdo da <em>Tela 1</em></li><li><strong>Movie:</strong> responsável pelo conteúdo da <em>Tela 2</em></li></ul><p>Abaixo, apresentamos o código do <em>container</em> <strong>Header</strong>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/67f7d3d77229a9cd055483dfc9ab2ac5/href">https://medium.com/media/67f7d3d77229a9cd055483dfc9ab2ac5/href</a></iframe><p>Dentro da parte <em>componentDidMount </em>do ciclo do react, disparamos a operação <em>load</em> para os recursos <em>“profile”</em> e<em> “wallet”. </em>Na função <em>render</em>, checamos o estado dos recursos e, baseado neles, decidimos o que mostrar na tela. Os nomes <em>isPristine</em>, <em>isLoading</em> e <em>hasLoadError </em>são <a href="https://github.com/zup-next/redux-resource#utilities-for-checking-the-operation-status">funções utilitárias</a> providenciadas pela nossa biblioteca, mas se elas não te agradam, você pode também verificar o estado da operação diretamente:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d667e9927ab6e010e8764774dc227578/href">https://medium.com/media/d667e9927ab6e010e8764774dc227578/href</a></iframe><p>Existem quatro estados possíveis para uma operação de um recurso: <em>“pristine”</em>, <em>“pending”</em>, <em>“success”</em> e <em>“error”</em>. Primeiro verificamos <em>“pristine”</em>, pois uma renderização é feita antes das operações de <em>load</em> serem disparadas e não queremos renderizar nada nesse caso.</p><p>As respostas para nossas requisições são retornadas no campo <em>“data”</em> dos recursos. Quando definimos a API (primeiro código apresentado neste artigo), dissemos ao <em>axios</em> para retornar apenas o payload na resposta, portanto, no nosso caso, <em>“data”</em> contém exatamente o payload das respostas retornadas pelo servidor.</p><p>Podemos usar a mesma ideia para construir os demais componentes. Abaixo, mostramos o código para o <em>container</em> <strong>Home</strong>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a5c27be0c4fed2916c1b981594022e40/href">https://medium.com/media/a5c27be0c4fed2916c1b981594022e40/href</a></iframe><p>E o <em>container</em> <strong>Movie</strong>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/747b080339cf6086d4154abb624ce936/href">https://medium.com/media/747b080339cf6086d4154abb624ce936/href</a></iframe><p>No container Movie.js , não estamos interessados no catálogo completo, mas apenas no filme com id igual ao parâmetro passado na URL. Portanto, selecionamos o filme que queremos do catálogo usando <em>findMovieById</em>. Em aplicações reais, seria preferível utilizar o <a href="https://github.com/reduxjs/reselect"><em>reselect</em></a> para <em>memoizar</em> o filme, já que rodar um <em>findBy </em>dentro do método render pode ser muito caro.</p><p>Legal! Já criamos três dos nossos quatro <em>containers</em>! Nesta parte conseguimos implementar a maior parte da aplicação usando três request diferentes sem escrever se quer uma linha de ação, <em>reducer</em> ou saga! Pode até não parecer muito nesta aplicação simples, mas isso economiza muito tempo em <em>apps</em> reais. Além disso, também criamos uma forma muito bem definida de escrever nossas interações com as APIs, o que ajuda, e muito, na manutenção do código.</p><p>Na parte seguinte (Parte 2), vamos implementar a terceira tela: a interface de pagamento. Para isso, vamos usar a operação <em>“create”</em> e algumas outras ações para controlar seu comportamento. Nos vemos lá!</p><p>Interessados em <em>hooks</em>, <em>typescript</em> e <em>cache</em>? O projeto <a href="https://github.com/zup-next/react-demos/tree/master/demo-typescript"><em>demo-typescript</em></a>, em nosso repositório de demos, implementa esse mesmo projeto usando <em>typescript</em> ao invés de <em>javascript</em>. O projeto <a href="https://github.com/zup-next/react-demos/tree/master/demo-hooks"><em>demo-hooks</em></a>, além de usar <em>typescript</em>, usa <em>hooks</em> e ainda configura um <em>cache</em> inteligente para a aplicação <em>(spoiler alert: hooks rocks!)</em>. Sobre o cache, ainda vamos falar bastante sobre isso na terceira e última parte desta série de artigos, aguarde.</p><p>Você pode ter notado também a natureza estática dos recursos que criamos. Se chamarmos o <em>load</em> de um recurso duas vezes, por exemplo, o conteúdo atual seria substituído pelo novo. Esse comportamento funciona muito bem para a maioria das situações, mas e se quiséssemos recuperar dois filmes (através de uma URL do tipo <em>“/movies/{id}”</em>) e exibí-los lado-a-lado? A biblioteca <em>redux-resource</em> também disponibiliza a função <em>createDynamicResource</em> exatamente para esses casos. Se precisar usá-la, dê uma olhada na <a href="https://github.com/zup-next/redux-resource#dynamic-resources">nossa documentação</a> e no demo <a href="https://github.com/zup-next/react-demos/tree/master/demo-dynamic-resource"><em>demo-dynamic-resource</em></a>.</p><p>Deixo aqui meus agradecimentos aos demais autores da biblioteca e revisores deste texto: <a href="https://medium.com/u/49ed2ffd70d7">Isac</a> e <a href="https://medium.com/u/f7008b32ef7c">Raphael de Souza</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a13dba7ca446" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Request management made easy with @zup-next libraries for react: Part 3.]]></title>
            <link>https://medium.com/@tiagoperesfr/request-management-made-easy-with-zup-next-libraries-for-react-part-3-26c1d362eb5c?source=rss-23b2489b87ba------2</link>
            <guid isPermaLink="false">https://medium.com/p/26c1d362eb5c</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[redux-saga]]></category>
            <category><![CDATA[redux]]></category>
            <dc:creator><![CDATA[Tiago Peres França]]></dc:creator>
            <pubDate>Tue, 28 May 2019 19:06:20 GMT</pubDate>
            <atom:updated>2019-05-28T19:06:20.919Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Nz5u_0YVPagLTxt2zKpogA.png" /></figure><p>Welcome to the third and last part of this series of articles. If you didn’t read the previous parts yet, you can find them in the following links: <a href="https://medium.com/@tiagoperesfr/request-management-made-easy-with-zup-next-libraries-for-react-part-1-b89dda8abac9">Part 1</a>, <a href="https://medium.com/@raphael.soms/request-management-made-easy-with-zup-next-libraries-for-react-part-2-30b965833682">Part 2</a>. The complete code for the demo application that we’re building in this series of articles can be found <a href="https://github.com/zup-next/react-demos/tree/master/demo-simple">here</a>.</p><h3>Motivation</h3><p>We, front-end coders, are directly responsible for the user’s experience in our applications. Each micro-interaction, tweaks and improvements we make are made so the user might have a better time when using our products. At <a href="https://www.zup.com.br/">Zup-IT</a>, we have this concern, which was made apparent in one of our last projects where, although the application was functional and had great feedback from the client, we knew we could make it better by reducing the number of loadings through a more intelligent control of the requests we make.</p><p>It was following this line of thought that we decided to create the library which is the basis for this last part of the series. We’re going to talk about it now and better explain how it considerably improved many aspects of the application for our clients and also for us, developers.</p><h3>Improving the demo application</h3><p>Getting back to our demo application, we can say that it has already been implemented and works very well, but we can still make it better. If you open the Network panel, in the developer tools for Chrome, you’ll see that some resources are called multiple times when we don’t really need to be calling them again. The following image shows the state of the Network panel in the catalog screen just after placing an order for a movie.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2_B-756YtvripY9vZtrwDA.png" /><figcaption>Network panel after ordering a movie and showing the catalog (without cache)</figcaption></figure><p>Notice that the URL <em>“/catalog”</em> was called three times and the URL “<em>/wallet</em>” was called two times. Since the load operations happen in the <em>componentDidMount </em>phase of each component, every time these components are showed in the screen, the requests are triggered. We find situations like this in many applications, sometimes the page needs a resource that has already been loaded by another page, or, sometimes, the component is appearing for the second time and doesn’t need to fetch the resources it has already fetched in the first time.</p><p>We could fetch the resources in the first page they’re needed and never load them again, but this is a terrible idea. What if the user enters the page directly from the URL? Besides, when initializing each container, we’d need to know beforehand the resources that has already been loaded and the ones that has not, which would make our code a lot more complex.</p><p>Another solution would be to verify if a resource has already been loaded before loading it again. Unfortunately, in some situations, we really need to refresh the content. By doing this, we’d end up with a collection of “ifs” that could also make our code very complex in the future.</p><p>The solution we want is one capable of remembering the resources that have already been loaded and forget them at the right times, but we don’t want to add any complexity to our existing code. In our containers, we want to keep the simplicity of dispatching the action “load” of a resource every time we need it, without having to worry if it has already been fetched or not. i.e. we need an intelligent cache system that can be configured outside our containers. We named this system <a href="https://github.com/zup-next/redux-action-cache"><em>redux-action-cache</em></a>.</p><p>Since all of our load actions are managed by <a href="https://redux-saga.js.org/"><em>redux-saga</em></a>, we had the idea of intercepting the redux actions and take a decision of whether to process or not the action according to our needs.</p><p>The <em>redux-action-cache </em>is a middleware that allow us to cache actions from redux, i.e., every time an action is dispatched, before it can proceed, it goes through our middleware which acts like a gateway, deciding if the action will be ignored or if it’s going to proceed to the next middlewares and reducers. An action is ignored every time there’s a valid cache for it. The application starts with an empty cache, as soon as an action is dispatched, if there’s a cache rule for it, a cache is created, in a way that, if it’s dispatched again, it will be ignored until this cache is no longer valid.</p><p>It is very easy to set up the the <em>redux-action-cache</em>. We must first define the rules for our application, then we just need to register the middleware to redux. Attention: our middleware must be the first to be defined so it works as a gateway! It doesn’t matter if we ignore an action after it goes through <em>redux-saga</em>, for instance.</p><p>Getting back to our movie store application, we can extract the following cache rules:</p><ul><li>Cache every action where<em> “type”</em> ends with <em>“/LOAD”</em>. These action types are defined by <a href="https://github.com/zup-next/redux-resource"><em>redux-resource</em></a>. They are the value of the field <em>“types”</em> in the result of the function <em>“createResource”</em>. See <a href="https://github.com/zup-next/redux-resource#resourcetypes">here</a> a list with all action types.</li><li>The load actions must not be cached if an error occurs while making the request. It is, if we dispatch a <em>“/LOAD” </em>after a <em>“/LOAD_ERROR”</em>, <em>“/LOAD”</em> must be processed by redux, no matter if it has been cached before. In other words, every <em>“/LOAD_ERROR ”</em>must invalidate its corresponding <em>“/LOAD”.</em></li><li>The action <em>load</em> of the resource “wallet” must always be refetched after an order is successfully placed, i.e. an action of type <em>“ORDER/CREATE_SUCCESS”</em> must invalidate the cache of the action <em>“WALLET/LOAD”</em>.</li></ul><p>Having set up the rules for our application’s cache, we just need to write them in the format expected by the library <em>redux-action-cache</em>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/55e4e69898fda3fe13620f8c32121ae4/href">https://medium.com/media/55e4e69898fda3fe13620f8c32121ae4/href</a></iframe><p>In the code above, in <em>“include”</em>, we defined an array with all action types that must be cached. Another way of achieving the same result would be using a <em>regex</em>. See the example below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/81c35441b9872d6c305be7e09a8e547d/href">https://medium.com/media/81c35441b9872d6c305be7e09a8e547d/href</a></iframe><p>In the invalidations property, we need to use <em>regex</em> and capture groups to define that every action following the format <em>“(x)/LOAD-ERROR” </em>must invalidate the action <em>“(x)/LOAD”</em>. Instead of using <em>regex</em>, we could have written every error and load action, but the code would be way longer.</p><p>When creating the redux store, we need to include our middleware:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/055e21a462c6503563338a92f991afe0/href">https://medium.com/media/055e21a462c6503563338a92f991afe0/href</a></iframe><p>Done! It’s that simple! Now, if we run the application again, buy a movie and return to the catalog, we’ll see that only the necessary requests will be sent.</p><p>The catalog is now called only once! Many containers use it, but, in fact, the catalog is just one, there’s no need to reload it every time a container is mounted. The resource “wallet” continues to be called twice because, when setting the cache rules, we said that the cache for it should be invalidated every time an order is created.</p><p>The economy made is not much in this simple application, but in the real world, the <em>redux-action-cache </em>makes a huge difference with a very small code footprint. In the beginning of our conversation, we mentioned the importance of front-end developers to care about every detail of the experience they’re providing to the user. The <em>redux-action-cache</em> approach allowed us to improve the communication between the user and the application, lowering the number of requests sent to the server, which brought us many advantages, like the reduction in the number of loadings in the application and reduction of the usage in the back-end server.</p><p>Here we used a very simple configuration for the cache, but the library offers many customization options like: expiration, persistence and cache based on properties other than the action’s type. For more information, please, read <a href="https://github.com/zup-next/redux-action-cache">our documentation</a>.</p><p>We finally got to the end! Along these three articles, we created an application with <em>redux-resource</em> and <em>redux-action-cache</em>. Through these libraries, we made it possible to simplify all the code responsible for request management. Furthermore, we created an intelligent cache with a very easy configuration. Thank you for reading! If you have any idea or suggestion, do not hesitate using GitHub to create issues or submit pull requests. Below, we leave a list with the most useful links related to the content of this series of articles.</p><ul><li><a href="https://github.com/zup-next/redux-resource">Redux-resource</a></li><li><a href="https://github.com/zup-next/redux-action-cache">Redux-action-cache</a></li><li><a href="https://redux.js.org/">Redux</a></li><li><a href="https://redux-saga.js.org/">Redux-Saga</a></li><li><a href="https://github.com/zup-next/react-demos/tree/master/demo-simple">Projeto de demonstração no Github</a></li><li><a href="https://github.com/zup-next/react-demos/tree/master/demo-typescript">Projeto de demonstração no Github (typescript)</a></li><li><a href="https://github.com/zup-next/react-demos/tree/master/demo-hooks">Projeto de demonstração no Github (typescript e hooks)</a></li></ul><p>I’d like to thank my colleagues <a href="https://medium.com/u/49ed2ffd70d7">Isac</a> e <a href="https://medium.com/u/f7008b32ef7c">Raphael de Souza</a> for co-authoring the library and this article.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=26c1d362eb5c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Request management made easy with @zup-next libraries for react: Part 1.]]></title>
            <link>https://medium.com/@tiagoperesfr/request-management-made-easy-with-zup-next-libraries-for-react-part-1-b89dda8abac9?source=rss-23b2489b87ba------2</link>
            <guid isPermaLink="false">https://medium.com/p/b89dda8abac9</guid>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[redux-saga]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Tiago Peres França]]></dc:creator>
            <pubDate>Tue, 28 May 2019 18:53:24 GMT</pubDate>
            <atom:updated>2019-05-28T19:04:19.248Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UoOxRvJ571Q9o61kaf6KnA.png" /></figure><h3>Motivation</h3><p>We, at <a href="https://www.zup.com.br/">Zup IT</a>, usually use a set of utilities when dealing with request management in <em>react</em>. We recently decided to share them with the community through two different repositories: <a href="https://github.com/zup-next/redux-resource"><em>redux-resource</em></a> and <a href="https://github.com/zup-next/redux-action-cache"><em>redux-action-cache</em></a>. In this article we’re going to talk about the first one, which is responsible for creating almost everything we need to control our requests through the redux actions and state.</p><p>Let’s face it, creating action types, action creators, <a href="https://redux.js.org/basics/reducers">reducers</a> and <a href="https://redux-saga.js.org/">sagas</a> for every request is boring. It takes time and sometimes it gets hard to maintain. If we are using REST services, every GET, PUT, POST and DELETE is pretty much the same thing. Why are we recreating the code every time we need to call a new service? What if we also treat our requests as REST resources in the front end, can’t we then use the same treatment for every request and avoid code repetition? This is exactly what our<em> redux-resource</em> library intends to do!</p><h3>An application using our lib</h3><p>This article presents a simple application created with <em>redux-resource</em>. The application is an online movie store that allows the user to check their current balance, see a catalog of movies and place orders. The focus here will be on how to make the requests, so we won’t talk much about styles or other react components.</p><p>The demo project with the full code can be found <a href="https://github.com/zup-next/react-demos/tree/master/demo-simple">here</a>. You can follow the instructions in the readme of the repository to get it running. The following images illustrates how the application works:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Am6M2Fndttf7fSj0mrxByA.png" /><figcaption>Screen 1 (Home)</figcaption></figure><p>In the first screen, the user checks the balance and the catalog of movies available for purchasing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BAH8SQ__gmucHw2Y34zmFQ.png" /><figcaption>Screen 2 (Movie details)</figcaption></figure><p>The second screen shows the details of the movie chosen in the previous screen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q7ySNEOUeIR6zm3UMiE1sA.png" /><figcaption>Screen 3 (Payment)</figcaption></figure><p>The third and final screen is responsible for paying and placing an order.</p><p>In the first part of this series of articles, we’ll use the <em>Screen 1</em> and <em>Screen 2</em> to show the basic use of the library. In the second part, we’ll implement the third screen, enabling the user to pay for an order. And in the third and final part, we are going to address the problem of making multiple requests to the same url, introducing the library <em>redux-action-cache</em>.</p><h3>Writing the application</h3><p>The REST API we’re using to build this application offers the following services:</p><ul><li><strong>GET /profile:</strong> returns the user profile</li><li><strong>PUT /profile:</strong> updates the profile with the object passed in the payload</li><li><strong>GET /catalog:</strong> get the list of movies available</li><li><strong>GET /wallet:</strong> get an object with two properties: balance and cards. “Balance” is a number representing the user’s balance and “cards” is a list of credit cards.</li><li><strong>POST /wallet:</strong> adds a new credit card to the wallet</li><li><strong>DELETE /wallet:</strong> removes a credit card from the wallet</li><li><strong>POST /order:</strong> creates an order</li></ul><p>Attention: although http requests can be GET, POST, PUT or DELETE, the operations defined in <em>redux-resource</em> are load, create, update and remove.</p><p>We can identify three resources in the first two screens: the user profile, the balance (wallet) and the movie catalog. The first thing we must do is to create the API functions. We recommend using <a href="https://github.com/axios/axios"><em>axios</em></a> for this.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f7ac738f5f444535b5a3e86e2d5865e1/href">https://medium.com/media/f7ac738f5f444535b5a3e86e2d5865e1/href</a></iframe><p>Now that our API interface is set up, we can create the resources:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ce14def3a53d6154423aa9f8bf87f16b/href">https://medium.com/media/ce14def3a53d6154423aa9f8bf87f16b/href</a></iframe><p>It’s as simple as that! Every resource can have a load, update, create or remove operation. In this example, we used the operations update profile, create wallet and remove wallet just to illustrate how they could be used, we won’t call them in our demo project.</p><p>The function <em>createResource</em> returns an object with the keys:</p><ul><li>types: the action types (strings)</li><li>actions: the action creators (functions that create actions)</li><li>reducers: the reducers to input to redux</li><li>sagas: the sagas to input to <em>redux-saga</em></li></ul><p>We use the return value of <em>createResource</em> to create our store and dispatch actions. The following code shows how to create the redux store with the resources we created.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b3d33aa3db8b12de67ff53813727c641/href">https://medium.com/media/b3d33aa3db8b12de67ff53813727c641/href</a></iframe><p>Above, <em>combineReducers</em> is a typical function of redux, while <em>createEffects</em> is a utility function of our library responsible for creating the saga effects, it takes an object where each key is an action type and each value a generator function. For more details on <em>createEffects</em>, please, read <a href="https://github.com/zup-next/redux-resource#createeffectstypetosagamap-effect">our documentation</a>.</p><p>Now that we have set up the resources and the store, we can start using them! We divided the <em>Screen 1</em> and <em>Screen 2</em> into three containers:</p><ul><li><strong>Header:</strong> responsible for the header, shared by all screens</li><li><strong>Home:</strong> responsible for the content of the <em>Screen 1</em></li><li><strong>Movie:</strong> responsible for the content of the <em>Screen 2</em></li></ul><p>Below, we present the code for the <strong>Header</strong> container:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/67f7d3d77229a9cd055483dfc9ab2ac5/href">https://medium.com/media/67f7d3d77229a9cd055483dfc9ab2ac5/href</a></iframe><p>Inside the <em>componentDidMount</em> part of the react cycle, we dispatch the load operation for the resources “profile” and “wallet”. In the <em>render</em> function we check the status of our resources and, based on them, we decide what to show. <em>isPristine</em>, <em>isLoading</em> and <em>hasLoadError</em> are <a href="https://github.com/zup-next/redux-resource#utilities-for-checking-the-operation-status">helper functions</a> provided by our library, but if you don’t like them, you could check the status directly:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d667e9927ab6e010e8764774dc227578/href">https://medium.com/media/d667e9927ab6e010e8764774dc227578/href</a></iframe><p>We have four possible status for any resource operation, they are: “pristine”, “pending”, “success” and “error”. We first check for “pristine” because one render is done before <em>componentDidMount</em> is run and we don’t want to render anything before dispatching the actions to load the resources.</p><p>The responses for our requests will be returned in the field “data” of the resources. When defining the API (first code presented in this article), we told <em>axios</em> to return only the payload as the response, so, in our case, “data” will always contain the payload of the responses returned from the server.</p><p>We can use the same idea to build all other containers. Below we show the code for the <strong>Home</strong> container.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a5c27be0c4fed2916c1b981594022e40/href">https://medium.com/media/a5c27be0c4fed2916c1b981594022e40/href</a></iframe><p>And the <strong>Movie</strong> container:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/747b080339cf6086d4154abb624ce936/href">https://medium.com/media/747b080339cf6086d4154abb624ce936/href</a></iframe><p>In the container <em>Movie.js,</em> we are not interested in the entire catalog, but only in the movie with id equal to the URL parameter. So we select the movie we want from the catalog using <em>findMovieById</em>. In real world applications you’ll want to use <a href="https://github.com/reduxjs/reselect"><em>reselect</em></a> to memoize the movie, since running a <em>findBy</em> inside the render method can be expensive.</p><p>Nice! We created three of our four containers already! In this part we were able to implement most of the application using three different requests without writing a single action, reducer or saga! It might not look like much in this simple application, but it saves a lot of time and code in real world apps! Furthermore, we created a very well defined pattern of how to write our interactions with an API, which helps us a lot in maintenance!</p><p>In the <a href="https://medium.com/@raphael.soms/request-management-made-easy-with-zup-next-libraries-for-react-part-2-30b965833682">next part (Part 2)</a>, we’ll implement the third screen: the payment interface. For this, we’ll use the operation “create” and some other actions to control its behavior. See you there!</p><p>Interested in hooks, typescript and cache? The project <a href="https://github.com/zup-next/react-demos/tree/master/demo-typescript"><em>demo-typescript</em></a><em>, </em>in our repository of demos, implements this same project using typescript instead of javascript. The project <a href="https://github.com/zup-next/react-demos/tree/master/demo-hooks"><em>demo-hooks</em></a>, besides using typescript, uses hooks and also sets up an intelligent cache system for the application <em>(spoiler alert: hooks rocks!)</em>. About caching, we are still going to talk about it in the third and final part of this series of articles, wait for it!</p><p>You could also have noticed the static nature of the resources we created. If we call the load operation of a resource twice, for instance, the current content would get replaced by the new one. This behavior works very well in most of the cases, but what if we wanted to fetch two movies (through a URL like <em>“/movies/{id}”)</em> and show them side-by-side? The library <em>redux-resource </em>also provides the function <em>createDynamicResource</em> for these cases. If you need to use it, take a look at <a href="https://github.com/zup-next/redux-resource#dynamic-resources">our documentation</a> and the demo <a href="https://github.com/zup-next/react-demos/tree/master/demo-dynamic-resource"><em>demo-dynamic-resource</em></a>.</p><p>I’d like to thank my colleagues <a href="https://medium.com/u/49ed2ffd70d7">Isac</a> e <a href="https://medium.com/u/f7008b32ef7c">Raphael de Souza</a> for co-authoring the library and revising this article.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b89dda8abac9" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>