Zachary Palmer

Zachary Palmer

1559635491

Fetching Data from a Third-party API with Vue.js and Axios

Learn to build data-driven apps with Vue 2. Olayinka Omole creates a simple client to pull news stories from the New York Times API with the Axios library.

More often than not, when building your JavaScript application, you’ll want to fetch data from a remote source or consume an API. I recently looked into some publicly available APIs and found that there’s lots of cool stuff that can be done with data from these sources.

With Vue.js, you can literally build an app around one of these services and start serving content to users in minutes.

I’ll demonstrate how to build a simple news app that will show the top news articles of the day allow users to filter by their category of interest, fetching data from the New York Times API. You can find the complete code for this tutorial here.

Here’s what the final app will look like:

To follow along with this tutorial, you’ll need a very basic knowledge of Vue.js. You can find a great “getting started” guide for that here. I’ll also be using ES6 Syntax, and you can get a refresher on that here.

Project Structure

We’ll keep things very simple by limiting ourselves to just 2 files:

./app.js
./index.html


app.js will contain all the logic for our app, and the index.html file will contain our app’s main view.

We’ll start off with some basic markup in index.html:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>The greatest news app ever</title>
  </head>
  <body>
    <div class="container" id="app">
      <h3 class="text-center">VueNews</h3>
    </div>
  </body>
</html>


Next, include Vue.js and app.js at the bottom of index.html, just before the closing </body> tag:

<script src="https://unpkg.com/vue"></script>
<script src="app.js"></script>


Optionally, Foundation can be included, to take advantage of some pre-made styles and make our view look a bit nicer. Include this within the <head> tag:

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/foundation/6.3.1/css/foundation.min.css">


Creating a Simple Vue App

First, we’ll create a new Vue instance on the element div#app, and mock the response from the news API using some test data:

// ./app.js
const vm = new Vue({
  el: '#app',
  data: {
    results: [
      {title: "the very first post", abstract: "lorem ipsum some test dimpsum"},
      {title: "and then there was the second", abstract: "lorem ipsum some test dimsum"},
      {title: "third time's a charm", abstract: "lorem ipsum some test dimsum"},
      {title: "four the last time", abstract: "lorem ipsum some test dimsum"}
    ]
  }
});


We tell Vue what element to mount on, via the el option, and specify what data our app would be using via the data option.

To display this mock data in our app view, we can write this markup inside the #app element:

<!-- ./index.html -->
<div class="columns medium-3" v-for="result in results">
  <div class="card">
    <div class="card-divider">
      {{ result.title }}
    </div>
    <div class="card-section">
      <p>{{ result.abstract }}.</p>
    </div>
  </div>
</div>


The v-for directive is used for rendering our list of results. We also use double curly braces to show the contents of each of them.

Note: you can read more on the Vue Template Syntax here.

We now have the basic layout working:

Fetching Data from the API

To make use of the NYTimes API, you’ll need to get an API key. So if you don’t already have one, head over to their signup page and register to get an API key for the Top Stories API.

Making Ajax Requests and Handling Responses

Axios is a promise-based HTTP client for making Ajax requests, and will work great for our purposes. It provides a simple and rich API. It’s quite similar to the fetch API, but without the need to add a polyfill for older browsers, and some other subtleties.

Note: previously, *vue-resource* was commonly used with Vue projects, but it has been retired now.

Including axios:

<!-- ./index.html -->
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>


Now we can make a request to get a list of top stories from the home section, once our Vue app is mounted:

// ./app.js

const vm = new Vue({
  el: '#app',
  data: {
    results: []
  },
  mounted() {
    axios.get("https://api.nytimes.com/svc/topstories/v2/home.json?api-key=your_api_key")
    .then(response => {this.results = response.data.results})
  }
});


Remember: replace *your_api_key* with your actual API key obtained from the NYT Dev Network area.

Now we can see the news feed on our app homepage. Don’t worry about the distorted view; we’ll get to that in a bit:

The response from the NYT API looks like this, via Vue devtools:

Tip: Get Vue Devtools to make debugging Vue applications easier.

To make our work a bit neater and reusable, we’ll do some minor refactoring, and introduce a helper function for building our URLs. We’ll also register getPosts as a method for our application by adding it to the [methods](https://vuejs.org/v2/api/#methods "methods") object:

const NYTBaseUrl = "https://api.nytimes.com/svc/topstories/v2/";
const ApiKey = "your_api_key";

function buildUrl (url) {
  return NYTBaseUrl + url + ".json?api-key=" + ApiKey
}

const vm = new Vue({
  el: '#app',
  data: {
    results: []
  },
  mounted () {
    this.getPosts('home');
  },
  methods: {
    getPosts(section) {
      let url = buildUrl(section);
      axios.get(url).then((response) => {
        this.results = response.data.results;
      }).catch( error => { console.log(error); });
    }
  }
});


We can make some more changes to the way our view looks by introducing a computed property with some modifications to the original results returned from the API:

// ./app.js

const vm = new Vue({
  el: '#app',
  data: {
    results: []
  },
  mounted () {
    this.getPosts('home');
  },
  methods: {
    getPosts(section) {
      let url = buildUrl(section);
      axios.get(url).then((response) => {
        this.results = response.data.results;
      }).catch( error => { console.log(error); });
    }
  },
  computed: {
    processedPosts() {
      let posts = this.results;

      // Add image_url attribute
      posts.map(post => {
        let imgObj = post.multimedia.find(media => media.format === "superJumbo");
        post.image_url = imgObj ? imgObj.url : "http://placehold.it/300x200?text=N/A";
      });

      // Put Array into Chunks
      let i, j, chunkedArray = [], chunk = 4;
      for (i=0, j=0; i < posts.length; i += chunk, j++) {
        chunkedArray[j] = posts.slice(i,i+chunk);
      }
      return chunkedArray;
    }
  }
});


In the above code, in the processedPosts computed property, we attach an image_url attribute to each news article object. We do this by looping through the results from the API, and searching through the multimedia array of each result to find a media type with the format we need. We then assign the URL of that media to the image_url attribute. In cases where the media isn’t available, we make the default URL an image from Placehold.it.

We also write a loop to group our results array into chunks of four. This will take care of the distorted view we saw earlier.

Note: You can also easily do this chunking with a library like Lodash.

Computed properties are great for manipulating data. Instead of creating a method, and calling it every time we need to chunk our array of posts, we can simply define it as a computed property and use it as we wish, as Vue will automatically update the processedPosts computed property anytime results changes.

Computed properties are also cached based on their dependencies, so as long as results doesn’t change, the processedPosts property returns a cached version of itself. This will help with performance, especially when doing complex data manipulation.

Next, we edit our markup in index.html to show our computed results:

<!-- ./index.html -->
<div class="row" v-for="posts in processedPosts">
  <div class="columns large-3 medium-6" v-for="post in posts">
    <div class="card">
    <div class="card-divider">
      {{ post.title }}
    </div>
    <a :href="post.url" target="_blank"><img :src="post.image_url"></a>
    <div class="card-section">
      <p>{{ post.abstract }}</p>
    </div>
  </div>
  </div>
</div>


Now the app looks a tad better:

Introducing a News List Component

Components can be used to keep the application modular, and basically extend HTML. The “news list” can be refactored to a component so that, for example, if the app grows and a decision is made to use the news list anywhere else, it’ll be easy:

// ./app.js

Vue.component('news-list', {
  props: ['results'],
  template: `
    <section>
      <div class="row" v-for="posts in processedPosts">
        <div class="columns large-3 medium-6" v-for="post in posts">
          <div class="card">
          <div class="card-divider">
          {{ post.title }}
          </div>
          <a :href="post.url" target="_blank"><img :src="post.image_url"></a>
          <div class="card-section">
            <p>{{ post.abstract }}</p>
          </div>
        </div>
        </div>
      </div>
  </section>
  `,
  computed: {
    processedPosts() {
      let posts = this.results;

      // Add image_url attribute
      posts.map(post => {
        let imgObj = post.multimedia.find(media => media.format === "superJumbo");
        post.image_url = imgObj ? imgObj.url : "http://placehold.it/300x200?text=N/A";
      });

      // Put Array into Chunks
      let i, j, chunkedArray = [], chunk = 4;
      for (i=0, j=0; i < posts.length; i += chunk, j++) {
        chunkedArray[j] = posts.slice(i,i+chunk);
      }
      return chunkedArray;
    }
  }
});

const vm = new Vue({
  el: '#app',
  data: {
    results: []
  },
  mounted () {
    this.getPosts('home');
  },
  methods: {
    getPosts(section) {
      let url = buildUrl(section);
      axios.get(url).then((response) => {
        this.results = response.data.results;
      }).catch( error => { console.log(error); });
    }
  }
});


In the above code, we register a global component using the syntax Vue.component(tagName, options). It’s advisable to use a hyphen when defining tag names, so they don’t clash with any current or future standard HTML tags.

The additional options we introduced are explained as follows.

  • Props: this is an array of data we want to pass down the component from the parent scope. We added results because we load that from the main app instance.
  • Template: here we define the markup for the news list. Notice that we wrapped our list in a <section> tag. This is because a component needs to have a single root element, and not multiple ones (that would have been created by our div.row iteration).

Adjusting our markup to use our news-list component, and passing it the results data, looks like this:

<!-- ./index.html -->

<div class="container" id="app">
  <h3 class="text-center">VueNews</h3>
  <news-list :results="results"></news-list>
</div>


Note: components can also be created as single file components (*.vue** files), and then parsed by a build tool like webpack. Although this is beyond the scope of this tutorial, it’s recommended for larger or more complex applications.*

To take things further, you could even decide to go as far as making each article a component and make things even more modular.

Implementing Category Filters

To make our app richer, we can now introduce category filters to allow users to show only certain categories of news.

First, we’ll register the list of sections and the section being viewed in our app:

const SECTIONS = "home, arts, automobiles, books, business, fashion, food, health, insider, magazine, movies, national, nyregion, obituaries, opinion, politics, realestate, science, sports, sundayreview, technology, theater, tmagazine, travel, upshot, world"; // From NYTimes

const vm = new Vue({
  el: '#app',
  data: {
    results: [],
    sections: SECTIONS.split(', '), // create an array of the sections
    section: 'home', // set default section to 'home'
  },
  mounted () {
    this.getPosts(this.section);
  },
  // ....
});


Next, we can add this inside our div#app container:

<!-- ./index.html -->
<section class="callout secondary">
  <h5 class="text-center">Filter by Category</h5>
  <form>
    <div class="row">
      <div class="large-6 columns">
        <select v-model="section">
          <option v-for="section in sections" :value="section">{{ section }}</option>
        </select>
      </div>
      <div class="medium-6 columns">
        <a @click="getPosts(section)" class="button expanded">Retrieve</a>
      </div>
    </div>
  </form>
</section>


When the “Retrieve” button is clicked, we trigger the getPosts method for the selected section by listening for the click event with the syntax @click.

Final Touches and Demos

I decided to add some minor (optional) touches to make the app experience a little bit better, like introducing a loading image.

You can see a demo in the CodePen below (limited functionality):

See the Pen VueJS and NYTimes News App by SitePoint (@SitePoint) on CodePen.

Alternatively, you can view a live version here.

Conclusion

In this tutorial, we’ve learned how to start a Vue.js project from scratch, how to fetch data from an API using axios, and how to handle responses and manipulate data using components and computed properties.

Now we have a functional Vue.js 2.0 app, built around an API service. There are loads of improvements that could be made by plugging in some other APIs. For example, we could:

  • Props: this is an array of data we want to pass down the component from the parent scope. We added results because we load that from the main app instance.
  • Template: here we define the markup for the news list. Notice that we wrapped our list in a <section> tag. This is because a component needs to have a single root element, and not multiple ones (that would have been created by our div.row iteration).

… and so on.

The entire code for this project is also hosted on GitHub, so you can clone, run, and make any improvements you fancy.

Thanks for reading ❤

If you liked this post, share it with all of your programming buddies!

#vue-js #javascript

What is GEEK

Buddha Community

Fetching Data from a Third-party API with Vue.js and Axios
Aria Barnes

Aria Barnes

1625232484

Why is Vue JS the most Preferred Choice for Responsive Web Application Development?

For more than two decades, JavaScript has facilitated businesses to develop responsive web applications for their customers. Used both client and server-side, JavaScript enables you to bring dynamics to pages through expanded functionality and real-time modifications.

Did you know!

According to a web development survey 2020, JavaScript is the most used language for the 8th year, with 67.7% of people choosing it. With this came up several javascript frameworks for frontend, backend development, or even testing.

And one such framework is Vue.Js. It is used to build simple projects and can also be advanced to create sophisticated apps using state-of-the-art tools. Beyond that, some other solid reasons give Vuejs a thumbs up for responsive web application development.

Want to know them? Then follow this blog until the end. Through this article, I will describe all the reasons and benefits of Vue js development. So, stay tuned.

Vue.Js - A Brief Introduction

Released in the year 2014 for public use, Vue.Js is an open-source JavaScript framework used to create UIs and single-page applications. It has over 77.4 million likes on Github for creating intuitive web interfaces.

The recent version is Vue.js 2.6, and is the second most preferred framework according to Stack Overflow Developer Survey 2019.

Every Vue.js development company is widely using the framework across the world for responsive web application development. It is centered around the view layer, provides a lot of functionality for the view layer, and builds single-page web applications.

Some most astonishing stats about Vue.Js:

• Vue was ranked #2 in the Front End JavaScript Framework rankings in the State of JS 2019 survey by developers.

• Approximately 427k to 693k sites are built with Vue js, according to Wappalyzer and BuiltWith statistics of June 2020.

• According to the State of JS 2019 survey, 40.5% of JavaScript developers are currently using Vue, while 34.5% have shown keen interest in using it in the future.

• In Stack Overflow's Developer Survey 2020, Vue was ranked the 3rd most popular front-end JavaScript framework.

Why is Vue.Js so popular?

• High-speed run-time performance
• Vue.Js uses a virtual DOM.
• The main focus is on the core library, while the collaborating libraries handle other features such as global state management and routing.
• Vue.JS provides responsive visual components.

Top 7 Reasons to Choose Vue JS for Web Application Development

Vue js development has certain benefits, which will encourage you to use it in your projects. For example, Vue.js is similar to Angular and React in many aspects, and it continues to enjoy increasing popularity compared to other frameworks.

The framework is only 20 kilobytes in size, making it easy for you to download files instantly. Vue.js easily beats other frameworks when it comes to loading times and usage.

Take a look at the compelling advantages of using Vue.Js for web app development.

#1 Simple Integration

Vue.Js is popular because it allows you to integrate Vue.js into other frameworks such as React, enabling you to customize the project as per your needs and requirements.

It helps you build apps with Vue.js from scratch and introduce Vue.js elements into their existing apps. Due to its ease of integration, Vue.js is becoming a popular choice for web development as it can be used with various existing web applications.

You can feel free to include Vue.js CDN and start using it. Most third-party Vue components and libraries are additionally accessible and supported with the Vue.js CDN.

You don't need to set up node and npm to start using Vue.js. This implies that it helps develop new web applications, just like modifying previous applications.

The diversity of components allows you to create different types of web applications and replace existing frameworks. In addition, you can also choose to hire Vue js developers to use the technology to experiment with many other JavaScript applications.

#2 Easy to Understand

One of the main reasons for the growing popularity of Vue.Js is that the framework is straightforward to understand for individuals. This means that you can easily add Vue.Js to your web projects.

Also, Vue.Js has a well-defined architecture for storing your data with life-cycle and custom methods. Vue.Js also provides additional features such as watchers, directives, and computed properties, making it extremely easy to build modern apps and web applications with ease.

Another significant advantage of using the Vue.Js framework is that it makes it easy to build small and large-scale web applications in the shortest amount of time.

#3 Well-defined Ecosystem

The VueJS ecosystem is vibrant and well-defined, allowing Vue.Js development company to switch users to VueJS over other frameworks for web app development.

Without spending hours, you can easily find solutions to your problems. Furthermore, VueJs lets you choose only the building blocks you need.

Although the main focus of Vue is the view layer, with the help of Vue Router, Vue Test Utils, Vuex, and Vue CLI, you can find solutions and recommendations for frequently occurring problems.

The problems fall into these categories, and hence it becomes easy for programmers to get started with coding right away and not waste time figuring out how to use these tools.

The Vue ecosystem is easy to customize and scales between a library and a framework. Compared to other frameworks, its development speed is excellent, and it can also integrate different projects. This is the reason why most website development companies also prefer the Vue.Js ecosystem over others.

#4 Flexibility

Another benefit of going with Vue.Js for web app development needs is flexibility. Vue.Js provides an excellent level of flexibility. And makes it easier for web app development companies to write their templates in HTML, JavaScript, or pure JavaScript using virtual nodes.

Another significant benefit of using Vue.Js is that it makes it easier for developers to work with tools like templating engines, CSS preprocessors, and type checking tools like TypeScript.

#5 Two-Way Communication

Vue.Js is an excellent option for you because it encourages two-way communication. This has become possible with the MVVM architecture to handle HTML blocks. In this way, Vue.Js is very similar to Angular.Js, making it easier to handle HTML blocks as well.

With Vue.Js, two-way data binding is straightforward. This means that any changes made by the developer to the UI are passed to the data, and the changes made to the data are reflected in the UI.

This is also one reason why Vue.Js is also known as reactive because it can react to changes made to the data. This sets it apart from other libraries such as React.Js, which are designed to support only one-way communication.

#6 Detailed Documentation

One essential thing is well-defined documentation that helps you understand the required mechanism and build your application with ease. It shows all the options offered by the framework and related best practice examples.

Vue has excellent docs, and its API references are one of the best in the industry. They are well written, clear, and accessible in dealing with everything you need to know to build a Vue application.

Besides, the documentation at Vue.js is constantly improved and updated. It also includes a simple introductory guide and an excellent overview of the API. Perhaps, this is one of the most detailed documentation available for this type of language.

#7 Large Community Support

Support for the platform is impressive. In 2018, support continued to impress as every question was answered diligently. Over 6,200 problems were solved with an average resolution time of just six hours.

To support the community, there are frequent release cycles of updated information. Furthermore, the community continues to grow and develop with backend support from developers.



Wrapping Up

VueJS is an incredible choice for responsive web app development. Since it is lightweight and user-friendly, it builds a fast and integrated web application. The capabilities and potential of VueJS for web app development are extensive.

While Vuejs is simple to get started with, using it to build scalable web apps requires professionalism. Hence, you can approach a top Vue js development company in India to develop high-performing web apps.

Equipped with all the above features, it doesn't matter whether you want to build a small concept app or a full-fledged web app; Vue.Js is the most performant you can rely on.

Original source

 

#vue js development company #vue js development company in india #vue js development company india #vue js development services #vue js development #vue js development companies

Siphiwe  Nair

Siphiwe Nair

1620466520

Your Data Architecture: Simple Best Practices for Your Data Strategy

If you accumulate data on which you base your decision-making as an organization, you should probably think about your data architecture and possible best practices.

If you accumulate data on which you base your decision-making as an organization, you most probably need to think about your data architecture and consider possible best practices. Gaining a competitive edge, remaining customer-centric to the greatest extent possible, and streamlining processes to get on-the-button outcomes can all be traced back to an organization’s capacity to build a future-ready data architecture.

In what follows, we offer a short overview of the overarching capabilities of data architecture. These include user-centricity, elasticity, robustness, and the capacity to ensure the seamless flow of data at all times. Added to these are automation enablement, plus security and data governance considerations. These points from our checklist for what we perceive to be an anticipatory analytics ecosystem.

#big data #data science #big data analytics #data analysis #data architecture #data transformation #data platform #data strategy #cloud data platform #data acquisition

NBB: Ad-hoc CLJS Scripting on Node.js

Nbb

Not babashka. Node.js babashka!?

Ad-hoc CLJS scripting on Node.js.

Status

Experimental. Please report issues here.

Goals and features

Nbb's main goal is to make it easy to get started with ad hoc CLJS scripting on Node.js.

Additional goals and features are:

  • Fast startup without relying on a custom version of Node.js.
  • Small artifact (current size is around 1.2MB).
  • First class macros.
  • Support building small TUI apps using Reagent.
  • Complement babashka with libraries from the Node.js ecosystem.

Requirements

Nbb requires Node.js v12 or newer.

How does this tool work?

CLJS code is evaluated through SCI, the same interpreter that powers babashka. Because SCI works with advanced compilation, the bundle size, especially when combined with other dependencies, is smaller than what you get with self-hosted CLJS. That makes startup faster. The trade-off is that execution is less performant and that only a subset of CLJS is available (e.g. no deftype, yet).

Usage

Install nbb from NPM:

$ npm install nbb -g

Omit -g for a local install.

Try out an expression:

$ nbb -e '(+ 1 2 3)'
6

And then install some other NPM libraries to use in the script. E.g.:

$ npm install csv-parse shelljs zx

Create a script which uses the NPM libraries:

(ns script
  (:require ["csv-parse/lib/sync$default" :as csv-parse]
            ["fs" :as fs]
            ["path" :as path]
            ["shelljs$default" :as sh]
            ["term-size$default" :as term-size]
            ["zx$default" :as zx]
            ["zx$fs" :as zxfs]
            [nbb.core :refer [*file*]]))

(prn (path/resolve "."))

(prn (term-size))

(println (count (str (fs/readFileSync *file*))))

(prn (sh/ls "."))

(prn (csv-parse "foo,bar"))

(prn (zxfs/existsSync *file*))

(zx/$ #js ["ls"])

Call the script:

$ nbb script.cljs
"/private/tmp/test-script"
#js {:columns 216, :rows 47}
510
#js ["node_modules" "package-lock.json" "package.json" "script.cljs"]
#js [#js ["foo" "bar"]]
true
$ ls
node_modules
package-lock.json
package.json
script.cljs

Macros

Nbb has first class support for macros: you can define them right inside your .cljs file, like you are used to from JVM Clojure. Consider the plet macro to make working with promises more palatable:

(defmacro plet
  [bindings & body]
  (let [binding-pairs (reverse (partition 2 bindings))
        body (cons 'do body)]
    (reduce (fn [body [sym expr]]
              (let [expr (list '.resolve 'js/Promise expr)]
                (list '.then expr (list 'clojure.core/fn (vector sym)
                                        body))))
            body
            binding-pairs)))

Using this macro we can look async code more like sync code. Consider this puppeteer example:

(-> (.launch puppeteer)
      (.then (fn [browser]
               (-> (.newPage browser)
                   (.then (fn [page]
                            (-> (.goto page "https://clojure.org")
                                (.then #(.screenshot page #js{:path "screenshot.png"}))
                                (.catch #(js/console.log %))
                                (.then #(.close browser)))))))))

Using plet this becomes:

(plet [browser (.launch puppeteer)
       page (.newPage browser)
       _ (.goto page "https://clojure.org")
       _ (-> (.screenshot page #js{:path "screenshot.png"})
             (.catch #(js/console.log %)))]
      (.close browser))

See the puppeteer example for the full code.

Since v0.0.36, nbb includes promesa which is a library to deal with promises. The above plet macro is similar to promesa.core/let.

Startup time

$ time nbb -e '(+ 1 2 3)'
6
nbb -e '(+ 1 2 3)'   0.17s  user 0.02s system 109% cpu 0.168 total

The baseline startup time for a script is about 170ms seconds on my laptop. When invoked via npx this adds another 300ms or so, so for faster startup, either use a globally installed nbb or use $(npm bin)/nbb script.cljs to bypass npx.

Dependencies

NPM dependencies

Nbb does not depend on any NPM dependencies. All NPM libraries loaded by a script are resolved relative to that script. When using the Reagent module, React is resolved in the same way as any other NPM library.

Classpath

To load .cljs files from local paths or dependencies, you can use the --classpath argument. The current dir is added to the classpath automatically. So if there is a file foo/bar.cljs relative to your current dir, then you can load it via (:require [foo.bar :as fb]). Note that nbb uses the same naming conventions for namespaces and directories as other Clojure tools: foo-bar in the namespace name becomes foo_bar in the directory name.

To load dependencies from the Clojure ecosystem, you can use the Clojure CLI or babashka to download them and produce a classpath:

$ classpath="$(clojure -A:nbb -Spath -Sdeps '{:aliases {:nbb {:replace-deps {com.github.seancorfield/honeysql {:git/tag "v2.0.0-rc5" :git/sha "01c3a55"}}}}}')"

and then feed it to the --classpath argument:

$ nbb --classpath "$classpath" -e "(require '[honey.sql :as sql]) (sql/format {:select :foo :from :bar :where [:= :baz 2]})"
["SELECT foo FROM bar WHERE baz = ?" 2]

Currently nbb only reads from directories, not jar files, so you are encouraged to use git libs. Support for .jar files will be added later.

Current file

The name of the file that is currently being executed is available via nbb.core/*file* or on the metadata of vars:

(ns foo
  (:require [nbb.core :refer [*file*]]))

(prn *file*) ;; "/private/tmp/foo.cljs"

(defn f [])
(prn (:file (meta #'f))) ;; "/private/tmp/foo.cljs"

Reagent

Nbb includes reagent.core which will be lazily loaded when required. You can use this together with ink to create a TUI application:

$ npm install ink

ink-demo.cljs:

(ns ink-demo
  (:require ["ink" :refer [render Text]]
            [reagent.core :as r]))

(defonce state (r/atom 0))

(doseq [n (range 1 11)]
  (js/setTimeout #(swap! state inc) (* n 500)))

(defn hello []
  [:> Text {:color "green"} "Hello, world! " @state])

(render (r/as-element [hello]))

Promesa

Working with callbacks and promises can become tedious. Since nbb v0.0.36 the promesa.core namespace is included with the let and do! macros. An example:

(ns prom
  (:require [promesa.core :as p]))

(defn sleep [ms]
  (js/Promise.
   (fn [resolve _]
     (js/setTimeout resolve ms))))

(defn do-stuff
  []
  (p/do!
   (println "Doing stuff which takes a while")
   (sleep 1000)
   1))

(p/let [a (do-stuff)
        b (inc a)
        c (do-stuff)
        d (+ b c)]
  (prn d))
$ nbb prom.cljs
Doing stuff which takes a while
Doing stuff which takes a while
3

Also see API docs.

Js-interop

Since nbb v0.0.75 applied-science/js-interop is available:

(ns example
  (:require [applied-science.js-interop :as j]))

(def o (j/lit {:a 1 :b 2 :c {:d 1}}))

(prn (j/select-keys o [:a :b])) ;; #js {:a 1, :b 2}
(prn (j/get-in o [:c :d])) ;; 1

Most of this library is supported in nbb, except the following:

  • destructuring using :syms
  • property access using .-x notation. In nbb, you must use keywords.

See the example of what is currently supported.

Examples

See the examples directory for small examples.

Also check out these projects built with nbb:

API

See API documentation.

Migrating to shadow-cljs

See this gist on how to convert an nbb script or project to shadow-cljs.

Build

Prequisites:

  • babashka >= 0.4.0
  • Clojure CLI >= 1.10.3.933
  • Node.js 16.5.0 (lower version may work, but this is the one I used to build)

To build:

  • Clone and cd into this repo
  • bb release

Run bb tasks for more project-related tasks.

Download Details:
Author: borkdude
Download Link: Download The Source Code
Official Website: https://github.com/borkdude/nbb 
License: EPL-1.0

#node #javascript

Teresa  Bosco

Teresa Bosco

1598769720

Vue js Axios Tutorial

Vue js Axios Tutorial is today’s leading topic.  Axios is an excellent http client library. It uses promises by default and runs on both the client and the server. Axios is an impressive HTTP client library which lets you asynchronously issue HTTP requests to interact with REST endpoints. Consume REST APIs and make HTTP Requests is easy with Axios and Vue.js.

Vue js Axios Tutorial

We will use Axios to send an HTTP request to the Node.js server and fetch the data from the database and display it on the client side. We will make GET and POST request to the Node.js server. At the backend, we will use Express web framework. Okay, so first we need to install Vue.js using CLI. If you are not familiar with Vue cli, then please check out this Vue cli Tutorial.

#axios and vue.js #axios #vue cli #node.js #vue js

Roberta  Ward

Roberta Ward

1614918987

Fetching Data from a Third-party API with Vue.js and Axios

Learn how to start a new Vue project, fetch data from an API using Axios, and handle responses and manipulate data using components and computed properties.

More often than not, when building your JavaScript application, you’ll want to fetch data from a remote source or consume an API. There’s lots of cool stuff that can be done with data from a range of publicly available APIs.

With Vue.js, you can literally build an app around one of these services and start serving content to users in minutes.

I’ll demonstrate how to build a simple news app that will show the top news articles of the day, and that will allow users to filter by their category of interest, fetching data from the New York Times API. You can find the complete code for this tutorial here, and a live demo of the finished app here.

Here’s what the final app will look like:

vue-news-final-app

To follow along with this tutorial, you’ll need Node.js and (optionally) Yarn installed on your machine. To install Node, you can either head to the official download page and grab the Node binaries for your system, or use a version manager instead.

Once Node is installed, to pull in Yarn, run:

npm i -g yarn

You’ll also require a basic knowledge of Vue.js. You can find a great getting started guide for that here.

#vue #axios #javascript #api