Simple State Management in JavaScript with Nanny State

Nanny state There’s a small library that I wrote to help make it easier to build state-based web apps using vanilla JS. It is similar to React, but with far less overhead and new syntax to learn. It also uses a single app-wide state object instead of each individual component having its own state. It was inspired by HyperApp and has many similarities to Elm.

In this post, I’m going to explain how the nanny stat works and then demonstrate what it can do with a few examples.

Nanny State uses a one-way data flow model composed of 3 parts:

  • State – an object that stores all app data
  • Opinion – a function that returns a string of HTML based on the current state
  • Updates – a function that is the only way to change the state and re-render the view

In Nani Rajya, the state is everything. The State object is the only source of truth for your app – every bit of app data is a property of this object. Even the event handlers used in the view are methods of the state object.

The view is a representation of the state in the form of HTML. It changes whenever the state changes and allows users to interact with the app.

The update function is the only way the state can be changed. It is a single entry point for updating state and ensuring that changes are deterministic, consistent and predictable.

You need these 3 things to make an app in Nani State. In fact, it can be summarized by asking yourself the following 3 questions:

  1. What data do I need to store in my app? This will make the properties of State Thing
  2. How do I want the app data to be presented on the page? it will help you make View Celebration
  3. How will the app data change when the user interacts with it? Update This would require the function

Hello Granny State!

The easiest way to see how granny stat works is to write some code! We’ll start with a basic example and then try to build something more complex.

The easiest way to run the following example is to use an online code editor such as Codepen, or you can install and run it locally. nanny-state Package using NodeJS.

Copy the following code into the JS section of CodePen:

import  Nanny,html  from ';

const View = state => html`<h1>Hello $state.nameh1>`

const State = 
  name: "Nanny State",
  View


const Update = Nanny(State)

This shows how the 3 parts of the Nanny-state work together. Let’s look at each part separately:

const View = state => html`<h1>Hello $state.nameh1>`

nanny uses state µhtml HTML to render. View Celebration Always considers the objects of the state as his own Only parameter. it then uses html The function provided by μhtml to generate HTML based on the template literal provided as an argument to it.

Using template literal means we can use $variable Notation for inserting state properties into the view. In this example we are using it to enter the value of name inside the property

Element.

const State = 
  name: "Nanny State",
  View

State where is the object All App data is stored. This includes any properties and values ​​that will be displayed in View and may change over the life-cycle of the app, such as name In this example property.

notice that View is also the property of State Using object shorthand notation. remember state is everything – Every part of the app is the property of the state.

const Update = Nanny(State)

last line defines Update act as the return value of Nanny Celebration. It can now be used to update the value of any property State, really it Only any properties of the way State can be updated. It also does an initial render of View based on the values ​​provided in State, This means that a title will be displayed that says “Hello Nanny State” as can be seen in the codepen below:

see pen
Nani State – Hello Nani State (Sitepoint)
by DAZ (@daz4126) Feather codepen,

Although this example is basically just a static page. Let’s make this dynamic by adding an input box that allows the user to enter a name they want to say hello. Update the code so that it looks like the following:

import  Nanny,html  from ';

const View = state => html`<h1>Hello $state.nameh1><input oninput=$state.changeName>`

const changeName = event => Update(name: event.target.value)

const State = 
  name: "Nanny State",
  changeName,
  View


const Update = Nanny(State)

In this example we have added a elements for View, Event listeners are defined inline in the view, so in this example we have a oninput event listener attached Element. it will call changeName The event handler, which is a method of the State object, when any input is detected. This event listener needs to be defined, so let’s take a closer look:

const changeName = event => Update(name: event.target.value)

It’s a standard event handler written in vanilla JS. It accepts an event object as a parameter as usual and when it is called, we want to update it State object, so we use Update function, because this is the only way we can update State,

the argument we provide Update A function is an object that contains any properties we want to update to the state and associated new values. In this case we want to update name Property for the value entered by the user into the input field, which is part of the event object and is accessed using event.target.value, This will update the state with the new value from the input field and immediately re-render the page. Using µhtml for rendering means that only parts of View Get updated what has actually changed. This means that a. re-rendering afterState The update is both efficient and blazing fast.

And that’s it – your first nanny stat app! Try typing that and you’ll see how fast it responds to user input… and all with a few lines of code. You can see the code in the codepen below:

see pen
Nani State – Hello Nani State with Input (SitePoint)
by DAZ (@daz4126) Feather codepen,

Nanny State makes it extremely easy to write reactive state-based apps. As you can see, it doesn’t require a lot of code to build a dynamic state-based application that reacts to user interaction. This Nani is the beauty of the state.

True or False Quiz

Now that we’ve seen a basic example, let’s try to build something more complex. We will use Nanny State to make true or false quiz game. Open a new pen on the codepen and follow along.

We’ll start the same way, by importing the Nani State Library:

import  Nanny,html  from '

Next, we’ll create State Object and fill it with the initial property values ​​the game will use:

const State = 
  score: 0,
  index: 0,
  questions: [
    question: "A Nanny State is a country where nannies are employed by the state", answer: false,
    question: "Nanny State is also the name of a beer", answer: true,
    question: "Mila Kunis and Ashton Kutcher employ 16 nannies to help raise their children", answer: false,
    question: "The Nanny McPhee films are based on the Nurse Matilda books", answer: true,
    question: "Nanny State uses the µhtml library for rendering", answer: true,
]

This object has 3 properties:

  • score – Tracks how many questions the player has answered correctly and 0 . starts from
  • index – Tracks which question the player is up to and matches the last asset which is questions array.
  • questions – This is an array of objects question And answer Property. question property is a string and answer property is a boolean

Now that we have created the data, let’s create View To visualize that data:

const View = state => html`
<h1>True or False?h1>
<h2>Score: $state.scoreh2>
$state.index < state.questions.length ?
html`<p>$index + 1) $state.questions[state.index].questionp>
     <button onclick=$state.checkAnswer(true)>TRUEbutton>
     <button onclick=$state.checkAnswer(false)>FALSEbutton>`
:
html`<h2>Game Over, you scored $state.scoreh2>`
`

it’s a bit more complicated View But much of it should be fairly self-explanatory as we saw in the earlier example. After the title title, we display the score using score property of State Thing. Then we use a ternary operator to fork the view. Because the view is written using a template literal, you cannot use if-else statement for fork code, hence the need to use ternary statement.

This ternary statement checks whether questionNumber is less than the length of questions array, which is basically checking to see if there are still any questions left to answer. If there are, the question is displayed with two buttons, one for TRUE and one for FALSE. If there are no questions left we show a game over message with the player’s score.

One thing to note when forking view code using ternary operators is that you need to use html Tasks for each new fork.

Buttons both have an inline onclick The event listener is attached to those that call the same event handler, checkAnswer and accepts one’s argument true either false depending on which button was pressed. Now let’s write this event handler:

const checkAnswer = answer => event => Update(state => (
    score: answer === state.questions[state.index].answer ? state.score + 1 : state.score,
    index: state.index + 1
))

This event handler accepts an additional argument answer simultaneously event The object that all event handlers accept, so this needs to be done using the double arrow notation seen above. it calls Update function that uses a ternary operator to check whether the answer given as an argument matches the answer to the current question, if so score The asset is increased by 1, if not then the score remains the same. It also increases the value of index property, so the next question will be displayed.

This event handler now needs to be added to Statewith this View, We can do this using object shorthand notation, as long as checkAnswer And View are defined before State,

const State = 
  score: 0,
  index: 0,
  questions: [
    question: "A Nanny State is a country where nannies are employed by the state", answer: false,
    question: "Nanny State is also the name of a beer", answer: true,
    question: "Mila Kunis and Ashton Kutcher employ 16 nannies to help raise their children", answer: false,
    question: "The Nanny McPhee films are based on the Nurse Matilda books", answer: true,
    question: "Nanny State uses the µhtml library for rendering", answer: true,
],
  checkAnswer,
  View

Now that everything is part StateAll that remains to be done is to define Update work by calling Nanny work and provide State As an argument:

const Update = Nanny(State)

And all! The quiz should start running immediately and you should be able to answer each question and the score will change depending on whether the answer is correct or not. Another example of an interactive app that is quick to build with the least amount of code. Try answering the questions and see how you move on. You can see the finished code in the codepen below:

see pen
True or False Quiz – Sitepoint
by DAZ (@daz4126) Feather codepen,

Once you’ve had fun playing it and got used to how the Nanny stat works, here are some ideas for moving the game forward:

  • add more questions
  • Add ‘Start’ and ‘Play Again’ buttons to allow players to play again
  • select questions at random
  • keep track of the highest score
  • Add questions with other answers except true or false
  • Create a Multiple Choice Quiz

Nanny State includes plenty of other goodies like built-in support for using local storage and routing. See docs Contact us for more information or if you have any questions.

I’d love to hear what you think of Nanny State. Would you consider using it for a project? Would you like to know more about this? Leave a comment in our community!

Leave a Reply