Search code examples
htmlamp-htmlexpress-handlebars

Can I set a simple key-value pair using amp-state?


I am trying to set a simple {key: value} pair using amp-state. Currently in my code there I have to initialize on every set state for key - value pairs.

The project is using express-handlebar templates and AMP for state management in the templates. There is a default handlebar value for each key.

But when one value is changed I have to initialize all the amp state values. This leads to a lot of duplicate code that could be improved a lot by setting state an initial. But to refactor all amp state into a big object containing the key-value pairs will complicate my code quite a bit so i'd rather not use the exact examples you can find on amp documentation.

For example I would like to replace something like this:

tap:AMP.setState({
     lng: 'en',
     selectedVal: selectedVal || '{{baseVal}}',
     rate: rate || {{lookup currencyRates  baseCurrency}},
     symbol: symbol || '{{lookup symbols baseCurrency}}'
}),

with

tap:AMP.setState({
     lng: 'en', 
}),

In order to do this (and avoid errors) I would need to initialize all fields at the bottom of the page using <amp-state>...</amp-state> (and only changing the language in this case)

I tried to search for a solution, but I was not able. Does anyone know if there is a solution? If yes witch? If not, does anyone knows why?

Thanks in advice.


Solution

  • I finally found my answer. Maybe it will help others too.

    So even tough in the amp bind documentation there are no examples with just a key-value pair, seems like on this page there is. The conclusion is you can load a simple key-value pair by just inserting a simple string inside the script tag (similar to this example they have on the second page):

    <amp-state id="myText">
      <script type="application/json">
        "World"
      </script>
    </amp-state>
    

    I found it quite confusing because I was expecting that inside the script tag you should place a json object. But this seems to work just fine.