Polymer data layer for REST API interaction

Hey everyone, I’m trying to figure out how to set up a data layer in Polymer to work with a REST API. I’ve got a Go backend with a /api/list endpoint that handles GET and POST requests. I can fetch data using core-ajax, but I’m stuck on how to create new items via POST.

I’ve been at it for hours and I’m not sure if I’m doing it right. Here’s what I’ve come up with:

<polymer-element name='data-service' attributes='items'>
  <template>
    <core-ajax id='fetcher' auto url='/api/items' on-response='{{dataLoaded}}' handle-as='json'></core-ajax>
    <core-ajax id='creator' url='/api/items' on-response='{{itemCreated}}' method='POST' handle-as='json'></core-ajax>
  </template>
  <script>
    Polymer('data-service', {
      created: function() { this.items = []; },
      dataLoaded: function() { this.items = this.$.fetcher.response.slice(0); },
      addItem: function(name) {
        this.$.creator.body = JSON.stringify({name: name});
        this.$.creator.go();
      },
      itemCreated: function() { /* handle response */ }
    });
  </script>
</polymer-element>

Is this the right way to structure a data layer in Polymer? It feels clunky compared to working with local storage. Am I missing something? Thanks for any help!

Your approach is on the right track, but there are a few improvements you could consider. First, as others have mentioned, iron-ajax is indeed a more modern choice over core-ajax. Additionally, you might want to implement a loading state to handle the asynchronous nature of API calls. This can be done by adding a ‘loading’ property to your element and toggling it during requests.

For error handling, consider implementing a try-catch block in your methods. This will allow you to gracefully handle any network issues or unexpected responses. Lastly, you might want to explore using a separate data store (like Redux) for more complex applications, as it can provide better state management and data flow across your Polymer components.

Hey SwimmingFish, ur approach looks okay but have u thought about using iron-ajax? It’s newer and might work better. Also, for POST requests, u could add some error handling. Maybe smth like:

itemCreated: function(e, detail) {
  if (detail.response) {
    // handle success
  } else {
    // handle error
  }
}

just an idea. good luck!

hey there SwimmingFish! your approach looks pretty solid, but have you considered using iron-ajax instead of core-ajax? it’s more up-to-date and might give you better results. also, what about implementing a debounce for your POST requests? could help prevent accidental double-submissions. curious to hear how you handle error states - any thoughts on that?