Initializing state with <amp-state>

By default, the document state is empty, but we can add custom data with the amp-state component (amp-state is included with amp-bind). For example, we could set a state property for a customer's username like this:

<amp-state id="user">  <script type="application/json">    {      "username": "ruadhan"    }  </script></amp-state>

Note the id of the amp-state element. This would result in the following state:

{  user: {    username: "ruadhan"  }}

Whenever we create a state using the amp-state element, we access data within the state using the id of the element with dot or bracket syntax. So, user.username (or user[username]), in this case, would evaluate to ruadhan.

A neat thing about amp-state is that it can be fetched from ...

Get AMP: Building Accelerated Mobile Pages now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.