Karim Aya

Karim Aya

1556765451

Apollo state management in Vue application

This article assumes you already know what GraphQL and Apollo client are and you’re able to build Vue applications with Vue CLI## Why do we need Apollo local state management?

Imagine a Vue application fetching some data from a REST API. Where do you usually store this data? Probably, the answer would be ‘in the local component state’ or, if application is big enough, ‘in the Vuex store with the rest of data’. This answer makes sense, because we can have the single source of truth for our application.

Now imagine an application fetching data from a GraphQL endpoint with Apollo client. By default, Apollo will store this data to Apollo cache. But what if we have some local application state, stored in Vuex? If we copy data from Apollo cache to Vuex, we’re doubling our data. If we leave data from the API in Apollo and local data in Vuex, there will be two sources of truth. What would be a good way to store local data?

Previously there was a library named apollo-link-state to manage local data. But since Apollo 2.5 release, we don’t need it anymore because this functionality is now a part of Apollo core. So, we can simply manage our local state without adding any new dependencies 🎉

What are we going to build

Let’s try to create a simple to-do application with Vue and Apollo client.

I’ve started with a Vue CLI-powered to-do application with some custom styles. You can find its source code here.

Add Apollo to Vue application

First thing we need is to install Apollo client and integrate it to our Vue app. For integration, we will use vue-apollo plugin.

To install everything we need, type the following command in the terminal:

npm install --save vue-apollo graphql apollo-boost

or

yarn add vue-apollo graphql apollo-boost

Then open main.js file and add

// main.js

Vue.use(VueApollo);

This way we’re adding the vue-apollo plugin to our Vue application.

Now we need to configure our Apollo client. First, let’s add an import on the top of main.js file:

// main.js

import ApolloClient from 'apollo-boost';
// rest of imports

Vue.use(VueApollo);

Then, let’s create a client:

// main.js

import ApolloClient from 'apollo-boost';
// rest of imports

Vue.use(VueApollo);

const apolloClient = new ApolloClient({});

Add a provider based on this newly created client and inject it to Vue application instance:

// main.js

const apolloProvider = new VueApollo({
  defaultClient: apolloClient,
});

new Vue({
  render: h => h(App),
  apolloProvider, //here goes your Apollo provider
}).$mount('#app');

Now we’re ready to create an Apollo-powered store.

Initializing an Apollo cache

We’re going to initialize an Apollo cache where we will store our to-do items. Apollo has an InMemoryCache constructor to do this:

// main.js

import ApolloClient from 'apollo-boost';
import { InMemoryCache } from 'apollo-cache-inmemory';

// rest of imports

const cache = new InMemoryCache();

Now we need to add it to our client:

// main.js

const apolloClient = new ApolloClient({
  cache,
});

So far our cache is empty and we’re going to add some data to it. But first let’s create a local schema. This step could be optional, but just like how a schema is the first step toward defining our data model on the server, writing a local schema is the first step we take on the client.

Creating a local schema

Let’s think for a minute: what should our to-do item look like? It definitely needs to have some text but what else? Probably we need some property to define if it’s already done or not and also an ID to distinguish one todo-item from another. So, it should be an object with three properties:

{
  id: 'uniqueId',
  text: 'some text',
  done: false
}

Now we’re ready to add item type to GraphQL local schema.

Let’s create a new file resolvers.js in the src folder and add the following code to it

import gql from 'graphql-tag';

export const typeDefs = gql`
  type Item {
    id: ID!
    text: String!
    done: Boolean!
  }
`;

gql here stands for the JavaScript template literal tag that parses GraphQL query strings.

Awesome! Let’s import typeDefs and add them to our Apollo client:

// main.js

import ApolloClient from 'apollo-boost';
import { InMemoryCache } from 'apollo-cache-inmemory';
import { typeDefs } from './resolvers';
// rest of imports

const apolloClient = new ApolloClient({
  cache,
  typeDefs,
  resolvers: {},
});

Please note the empty resolvers object here: if we don’t assign it to the Apollo client options, it won’t recognize the queries to local state and will try to send a request to remote URL instead
Now we need to add some initial data to our cache. To directly write it here, we will use the writeQuery method:

// main.js

// apollo client code

cache.writeData({
  data: {
    todoItems: [
      {
        __typename: 'Item',
        id: 'dqdBHJGgjgjg',
        text: 'test',
        done: true,
      },
    ],
  },
});

// apollo provider code

We’ve just added an array of todoItems to our cache data and we are saying that every item has a type name of Item (specified in our local schema).

Now we’re ready to query our local data from our Vue component!

Query local data

First, we need to build a GraphQL query to retrieve the data. Let’s create a graphql folder, add a queries.js file to it and import graphql-tag there.

// queries.js

import gql from 'graphql-tag';

Now let’s write a query:

// queries.js

import gql from 'graphql-tag';

export const todoItemsQuery = gql`
  {
    todoItems @client {
      id
      text
      done
    }
  }
`;

So, we defined the name of the query here (todoItems) and we specified that this query should not be executed against remote GraqhQL API. @clientdirective here tells Apollo client it should fetch results in the local data store.

Finally, we’re ready to send the query from the Vue component. To do so, let’s open our App.vue, import the query constant there:



What’s going on here? We call the $apollo.mutate method (provided with vue-apollo plugin) and we pass the mutation we created earlier in queries.js and an id variable (ID is passed from the template where we’re checking the item):

<ListItem
  v-for="(item, index) in todoItems"
  :key="index"
  :content="item"
  @toggleDone="checkItem(item.id)"
  @delete="deleteItem(item.id)"
/>

Now when we’re clicking on the checkbox, we will send a mutation that changes our local state. We can see immediately that our todoItems array is changed with this mutation so checkbox becomes checked/unchecked.

Deleting an item

Now we need the way to delete an item. Let’s start again with creating a deleteItem mutation:

// queries.js

export const deleteItemMutation = gql`
  mutation($id: ID!) {
    deleteItem(id: $id) @client
  }
`;

As you can see, it’s very similar to the previous one: again, we’re passing an ID as a parameter. Now let’s add a resolver for it:

// resolvers.js

deleteItem: (_, { id }, { cache }) => {
  const data = cache.readQuery({ query: todoItemsQuery });
  const currentItem = data.todoItems.find(item => item.id === id);
  data.todoItems.splice(data.todoItems.indexOf(currentItem), 1);
  cache.writeQuery({ query: todoItemsQuery, data });
  return true;
},

Again, we’re reading the todoItemsQuery from the cache as a first step and writing it back later (and we’re simply returning true to show the request was successful). But instead of changing currentItem we’re just removing it from the todoItems array.

Now let’s add this mutation to the App.vue.



Very similar to checkItem, isn’t it?

Adding new item

While the two previous mutations were really similar to each other, addItemwill be different. First of all, we will pass a text, not an ID, and we want to be able to see what is actually added:

// queries.js

export const addItemMutation = gql`
  mutation($text: String!) {
    addItem(text: $text) @client {
      id
      text
      done
    }
  }
`;

You can assume the resolver will be more complex as well: we need to generate a unique ID somehow. For this project we’re going to use shortidlibrary:

npm install shortid

or

yarn add shortid

Now let’s start building our resolver:

// resolvers.js
import shortid from 'shortid';

export const resolvers = {
  Mutation: {
    ...
    addItem: (_, { text }, { cache }) => {
      const data = cache.readQuery({ query: todoItemsQuery });
      const newItem = {
        __typename: 'Item',
        id: shortid.generate(),
        text,
        done: false,
      };
    },
  }
}

As you can see, now we’re taking a text from our mutation arguments and set a newItem text property equal to it. For id we’re generating a new unique ID with shortid.generate method. As for done property, we always set it to false when creating a new todo-item (because obviously it’s not done yet!).

Now we need only to push this newly created item to the todoItems array, write the data back to the cache and return a newItem as a mutation result.

// resolvers.js

addItem: (_, { text }, { cache }) => {
  const data = cache.readQuery({ query: todoItemsQuery });
  const newItem = {
    __typename: 'Item',
    id: shortid.generate(),
    text,
    done: false,
  };
  data.todoItems.push(newItem);
  cache.writeQuery({ query: todoItemsQuery, data });
  return newItem;
},

We’re ready to call our addItem mutation from the component! Let’s import it to App.vue



…and add it to the addItem method:

  addItem() {
    if (this.newItem) {
      this.$apollo.mutate({
        mutation: addItemMutation,
        variables: { text: this.newItem }
      });
      this.newItem = "";
    }
  },

newItem here represents a string from the input field and we’re going to call a mutation only when we have some actual text to send. Also, after we’ve added a new item, we want to clear an input.

Yay, our application is ready! 🎉

You can find the full application source code here.

#vue-js #graphql #javascript

What is GEEK

Buddha Community

Apollo state management in Vue application
Luna  Mosciski

Luna Mosciski

1600583123

8 Popular Websites That Use The Vue.JS Framework

In this article, we are going to list out the most popular websites using Vue JS as their frontend framework.

Vue JS is one of those elite progressive JavaScript frameworks that has huge demand in the web development industry. Many popular websites are developed using Vue in their frontend development because of its imperative features.

This framework was created by Evan You and still it is maintained by his private team members. Vue is of course an open-source framework which is based on MVVM concept (Model-view view-Model) and used extensively in building sublime user-interfaces and also considered a prime choice for developing single-page heavy applications.

Released in February 2014, Vue JS has gained 64,828 stars on Github, making it very popular in recent times.

Evan used Angular JS on many operations while working for Google and integrated many features in Vue to cover the flaws of Angular.

“I figured, what if I could just extract the part that I really liked about Angular and build something really lightweight." - Evan You

#vuejs #vue #vue-with-laravel #vue-top-story #vue-3 #build-vue-frontend #vue-in-laravel #vue.js

Dock  Koelpin

Dock Koelpin

1598283829

Build a CRUD Application with Hasura and Vue-Apollo

In this tutorial, we would be building a simple Vue application with Hasura and Vue-Apollo that allows you to add, delete, and get all books you have read.

Prerequisites

  • Familiarity with HTML, CSS and JavaScript
  • Basic Knowledge of Vuejs
  • Basic Knowledge of Graphql
  • GraphQL Playground app. Download here
  • VS Code or any other code editor

App Requirements

  • Hasura: It’s an open-source graphql service that gives you instant realtime graphql APIs with PostGre database.
  • Heroku: We would be using heroku for hosting the API.
  • Vue-Apollo: This integrates ApolloClient in our Vue app with declarative components. We would use vue-apollo to consume our graphQL API

GraphQL is a query language for your APIs and runtime for consuming those queries with your existing data. Simply, it gives you the luxury of asking for a specific kind of data from your server and getting expected results.

GraphQL has two parts:

  • The Server: GraphQL server simply exposes your API via a single endpoint. APIs here are written as a series of type definitions and resolvers. Graphql gives you a variety of server libraries to expose your APIs.
  • The Client: GraphQL client accepts queries on the frontend, connects to the server endpoint, and ask for the data you want to receive. They are also a variety of client libraries and JavaScript has a handful including popular libraries such as AWS Amplify and ApolloClient.

Let’s get started with coding already

Building the API and setting up DB with Hasura

Let’s get our API and database ready. Follow these steps:

  • Go to hasura.io and sign up. Then click the Start for free button.
  • Create my first project and then choose heroku (sign up if you don’t have an account) for Database Setup.
  • Give it some seconds, and it’ll generate a postgre uri, copy it and store somewhere. Next page would have your console details, you can screenshot them too. You should also get your graphql API url. Something like this: this
  • Now we are here in the hasura graphql console, let’s create our database tables and relationships.

Setting up database Navigate to the Data tab. We would just be working with a single table called books. Click the add table on the left sidebar of the console. Follow these steps:

  • Give the table a name, i’m calling mine, “books” but you can decide to call yours anything else.
  • Create a column, name it “id”, set column_type to integer(auto-increment) and select the Unique checkbox.
  • Create another column, name it “title” and set column_type to text. Create 2 other columns, name them description and written_by and set their column_type to text.
  • Create a column, name it is_completed, set the column_type to date and default to now().
  • On the Primary Key field, select the id. Then click on Add table, this should successfully create your books table.

At the end, you should have something like this:

At the moment, our table has no rows. Let’s create some. Click on the Insert Row tab and add some content to the empty fields (text, description and written_by). You should have something like this when you browse rows:

#graphql #tutorials #vue #crud application #hasura #vue-apollo

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

Myriam  Rogahn

Myriam Rogahn

1599604560

Reactive Vue 3 State

Introduction

There’s been a lot of discussion about state management in the upcoming Vue 3 framework. Some writers go as far as declaring Vuex dead. Reactivity is all we need, is the claim. Just like blockchain was supposed to cure all problems of modern civilization ;-) Jokes aside, it does look like an intriguing possibility, so we’ve taken a challenge and explored it in this article.

TL;DR

Vue 3 Reactivity System, now free of UI confines, can be efficiently employed as a powerful tool to handle state. This requires extra plumbing though, with no batteries included. If you want to get straight to technical details, scroll down to Reactive proposal for application state chapter below.

The source code for the article can be found at https://bitbucket.org/letsdebugit/vue-3-state. It uses the simple build-less architecture presented in my recent article about Vue JS 3 Application Without Build.

No Need for Vuex?

I’ve seen many brilliant proposals for managing state using Vue 3 reactivity system. Some would end with a bold conclusion: Vuex is no longer needed. On closer inspection I wasn’t so sure. However ingenious, many proposals are essentially just another singleton with a bunch of methods, only made reactive. In all fairness this was perfectly doable with Vue 2 - yet we kept using Vuex. Why? Because there are deeper reasons why we got Vuex, Redux etc. Allow me now to stir a controversy:

A singleton with a bunch of methods is not a replacement for Vuex, even if it’s reactive.

What Makes a Good Application State?

A viable solution for application state must include the following:

  • Centralized state available to all components. We used to call it a store.
  • Functions to safely modify the state, routinely called mutations.
  • Ability to modify state in async functions such as API calls. Vuex makes it possible through actions, Redux offers thunks.
  • Prevent programmer from shooting himself in the foot by modifying state directly.

It is the last requirement which lacks in majority of the proposals. And for me it is a crucial requirement.

All the effort of writing proper state and mutations is waste of time, if my colleagues are free to modify and hack state directly, causing inconsistencies and elusive bugs.

Vuex helps enforce this with strict mode, which throws exceptions on attempts to illegally alter the state. Redux resorts to immutability - any local alterations will simply be discarded with the next mutation cycle.

Finally, the mere fact of using Vuex (or Redux etc.) enforces structure and discipline. It does come with the inevitable boilerplate code. But then one simply has to follow the structure - design a state store, define state mutations, organize application logic into actions, create state getters when state gets complex etc.

#javascript #web development #design pattens #vuejs #vue #state management #web application architecture

Origin Scale

Origin Scale

1616572311

Originscale Order Management System

Originscale order management software helps to manage all your orders across channels in a single place. Originscale collects orders across multiple channels in real-time - online, offline, D2C, B2B, and more. View all your orders in one single window and process them with a simple click.

#order management system #ordering management system #order management software #free order management software #purchase order management software #best order management software