---
description: Advanced State Operations - Events
---

# State Events

## Introduction

In the last chapter, we learned how we can use the state subscription methods to react to different actions taken on the state. Now we will learn to create custom events for our own purposes, that might be retrieving localStorage data when the component loads, or such things.

There are two methods of the `State` that does this,

* `registerEvent(...)` registers the custom event with a callback, that is expected to be called when the following custom event is emited, using
* `emitEvent(...)` which takes the name of the event as well as any data that might be related to it. The data is then passed to the callback function and the event is completed.

{% hint style="info" %}
You cannot register multiple functions under a single event name, which is simillar to the document.addEventListener() method.
{% endhint %}

Here is an example that retrieves the value from the localStorage:

```typescript
import { $, DebugRender, State, onLoad } from '@weblabsjs/core'
import { div, input, p } from '@weblabsjs/core/components'

function App() {

    const text = State<string>("")

    //now time to text custom events
    text.registerEvent<string>("localStorage", (name: string) => {

        text.set( localStorage.getItem(name) || "No data" )

    })

    onLoad(() => {

        text.emitEvent("localStorage", "data")

    })

    return div(
        input().prop("placeholder", "Enter text")
            .event("input", (e: any) => text.set(e.target.value)),

        $(() => p(text.get()), text)
    )
}

DebugRender("app", App)
```

In the above code, we declared the event which will take `string` data, the name of the item to retrieve from the localStorage. If it does not exists, it will simply set the text to No data, which means we can do state operations directly from event callbacks.

## Purpose

The purpose is again to create fine grained reactivity that does not breaks, since it is easier to track errors in callback. Also, many of our upcoming libraries will use custom events to deliver super experience.
