Search code examples
xmlhttprequestaxiosstenciljs

http requests in stenciljs


How can I make http requests (GET / POST / PUT / DELETE) in StencilJS?

I tried using axios as follows: Did npm install axios --save and in the stencil component import axios from 'axios';. As soon as I call axios.get(...)I get the following error message:


[ ERROR ] bundling: node_modules/axios/lib/adapters/http.js, line: 4

A module cannot import itself

L3: var utils = require('./../utils');

L4: var settle = require('./../core/settle');

L5: var buildURL = require('./../helpers/buildURL');


I understand it might have to do with this issue: https://github.com/ionic-team/stencil/issues/98

However, any recommendations on how to get html requests work within a stencil component?


Solution

  • We can use the fetch API. It is browser native and does therefore not need an import. StencilJS also has a polyfill for it, so it works everywhere.

    Thanks to @insanicae for pointing me to it.

    Example:

    import { Component, State } from '@stencil/core';
    
    @Component({
      tag: 'app-profile',
      styleUrl: 'app-profile.css'
    })
    export class AppProfile {
      @State() name: string;
    
      componentWillLoad() {
        fetch('https://api.github.com/users/ErvinLlojku')
          .then((response: Response) => response.json())
          .then(response => {
            this.name = response['name'];
          });
      }
    
      render() {
        return [
          <ion-header>
            <ion-toolbar color="primary">
              <ion-buttons slot="start">
                <ion-back-button defaultHref="/" />
              </ion-buttons>
              <ion-title>Profile: {this.name}</ion-title>
            </ion-toolbar>
          </ion-header>,
    
          <ion-content padding>
            <p>My name is {this.name}.</p>
    
          </ion-content>
        ];
      }
    }
    

    Consult official docs of fetch for more. https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API