How to add an object to an amp-state array in AMP-HTML?

1.4k Views Asked by At

I have a state called currentItem with url, title, description... When I push a button, a currentItem should be saved in other state called myItems. It will contains a list of items objects.

The problem right now is that it always shows the last item, so it is overwriting the entire list for each currentItem submit.

My States:

    <amp-state id="currentItem">
        <script type="application/json">
            {
                "url": "",
                "imageUrl": "",
                "title": "",
                "description": ""
            }
        </script>
    </amp-state>
    <amp-state id="myItems">
        <script type="application/json">
            []
        </script>
    </amp-state>

The list definition:

<amp-list class="mt3"
          layout="fixed-height"
          height="0"
          [src]="myItems"
          [height]="myItems.length * 200"
          items="."
          binding="no">
<template type="amp-mustache">
...
</template>

The action to add currentItem to the list:

<button type="button"
        on="tap:AMP.setState({ myItems: [currentItem]})">
Add
</button>

I tried using AMP.setState({ myItems: myItems.concat(currentItem)}) but it crash, also with +. How can I do that?

1

There are 1 best solutions below

2
On BEST ANSWER

concat expects an array. Here is the working version:

 <amp-state id="currentItem">
    <script type="application/json">
      {
        "url": "url",
        "imageUrl": "imageUrl",
        "title": "title",
        "description": "desc"
      }
    </script>
  </amp-state>
  <amp-state id="myItems">
    <script type="application/json">
      []
    </script>
  </amp-state>
  <h1>Hello AMPHTML World!</h1>
  <amp-list class="mt3" layout="fixed-height" height="0" [src]="myItems" [height]="myItems.length * 200" items="." binding="no">
    <template type="amp-mustache">
      Item: {{title}}
    </template>
  </amp-list>
  <button type="button" on="tap:AMP.setState({ 
                                myItems: myItems.concat([currentItem])
                            })">
    Add
  </button>