State management patterns in JavaScript: Sharing data across components

State management patterns in JavaScript: Sharing data across components

When we talk about state management what we are really talking about is, how do we manage data across the components of a JavaScript application?

When we talk about state management what we are really talking about is, how do we manage data across the components of a JavaScript application?

A typical challenge found in building many applications is keeping different parts of the user interface synchronized. Often, changes to the state need to be reflected in multiple components, and as the application grows this complexity only increases.

A common solution is to use events to let different parts of the application know when something has changed. Another approach is to keep state within the DOM itself or even assign it to a global object in the window. Nowadays we have several libraries such as Vuex, Redux, and NgRx to help make managing state across components easy. They generally use what is known as a store pattern where all actions that mutate or change the store’s state are put inside a single Store class. This type of centralized state management makes it easier to understand what type of mutations could happen and how they are triggered.

What we will build

Any state management tool needs only a couple of things: a global state value available to the entire application, as well as the ability to read and update it. The general idea is as follows:

const state = {};

export const getState = () => state;

export const setState = nextState => {
  state = nextState;
};

This is a very basic example that shows a globally-available value representing the application’s state: state, a method for reading state: getState and a method for updating state: setState. We would use this general idea to build a to-do list application with no JavaScript frameworks or dependencies. In the process, we will get a broad overview of how these state libraries work under the hood. The application will look like this:

To begin, we want to install http-server which will serve our application after we are done. To install this, first make sure you have Nodes.js and the Nodes.js package manager (NPM) installed on your machine. On a Windows operating system, the steps to install these are:

  1. Download the Windows installer from the Nodes.js web site
  2. Run the installer you just downloaded
  3. Follow the prompts, accepting the default installation settings
  4. Test it by running node-v in the terminal. This should print a version number so you’ll see something like this v8.12.0\. Also, run npm -v to see if NPM was successfully installed. This should print NPM’s version number so you’ll see something like this 6.4.1.
  5. Run the command npm install http-server -g to install http-server globally on your machine. After this is installed, you can now serve your application by running http-server in the directory where your index file exists

Now moving back to building our application, create a folder structure as shown below:

/state-management-JS
   ├──src
      ├── css
         ├── global.css
      ├── js
         ├── main.js
      index.html

In the global.css file, enter the following:

h1 {
    margin-bottom: 15px;
    width: 100%;
    font-size: 100px;
    font-weight: 100;
    text-align: center;
    color: rgba(175, 47, 47, 0.15);
    -webkit-text-rendering: optimizeLegibility;
    -moz-text-rendering: optimizeLegibility;
    text-rendering: optimizeLegibility;
}
@media all and (min-width: 40em) {
    main {
        width: 80vw;
        max-width: 40em;
        margin: 0 auto
    }
}
/**
* Intro 
*/
.intro {
    padding: 0 0 1rem 0;
    margin: 0 0 2rem 0;
    border-bottom: 1px dotted var(--border);
}
.intro__heading {
    font-weight: 400;
}
.intro__summary {
    margin-top: 0.3rem;
    font-size: 1.3rem;
    font-weight: 300;
}
.intro__summary b {
    font-weight: 500;
}
/**
* App 
*/
.app {
    display: grid;
    grid-template-columns: 1fr;
    grid-auto-flow: row;
    grid-gap: 2rem;
}
.app__decor {
    display: block;
    width: 100%;
    text-align: center;
    font-size: 3rem;
    line-height: 1;
}
.app__decor small {
    display: block;
    font-size: 1.3rem;
    font-weight: 400;
    color: var(--text-secondary);
}
.app__decor > * {
    display: block;
}
.app__decor > * + * {
    margin-top: 0.4rem;
}
.app__items {
    list-style: none;
    padding: 0;
    margin: 1rem 0 0 0;
    font-weight: 300;
}
.app__items li {
    position: relative;
    padding: 0 0 0 2rem;
    font-size: 1.3rem;
}
.app__items li::before {
    content: "🕛";
    position: absolute;
    top: 1px;
    left: 0;
}
.app__items li + li {
    margin-top: 0.5rem;
}
.app__items button {
    background: transparent;
    border: none;
    position: relative;
    top: -1px;
    color: var(--danger);
    font-weight: 500;
    font-size: 1rem;
    margin: 0 0 0 5px;
    cursor: pointer;
}
.app__items button:hover {
    color: var(--danger--dark);
}
@media all and (min-width: 40rem) {
    .app {
        grid-template-columns: 2fr 1fr;
    }
}

/**
* New item
*/
.new-item {
    margin: 2rem 0 0 0;
    padding: 1rem 0 0 0;
    border-top: 1px dotted var(--border);
}

/**
* No items
*/
.no-items {
    margin: 1rem 0 0 0;
    color: var(--text-secondary);
}
/**
* Visually hidden
*/
.visually-hidden { 
    display: block;
    height: 1px;
    width: 1px;
    overflow: hidden;
    clip: rect(1px 1px 1px 1px);
    clip: rect(1px, 1px, 1px, 1px);
    clip-path: inset(1px);
    white-space: nowrap;
    position: absolute;
}
.new-todo {
    padding: 16px 16px 16px 60px;
    border: none;
    background: rgba(0, 0, 0, 0.003);
    box-shadow: inset 0 -2px 1px rgba(0,0,0,0.03);
    position: relative;
    width: 100%;
    font-size: 24px;
    font-family: inherit;
    font-weight: inherit;
    line-height: 1.4em;
}
.save-button {
    display: inline-block;
    border: 0;
    padding: 0;
    margin: 0;
    text-decoration: none;
    background: #666;
    color: #fff;
    padding: 11px 25px 10px 25px;
    font-family: sans-serif;
    font-size: 1rem;
    border-radius: 2px;
    cursor: pointer;
    text-align: center;
    -webkit-appearance: none;
    margin-top: 15px;
}

This is the style-sheet we will use for our application. We won’t talk about styles in this tutorial as there is nothing specific about applying styles to the application.

The Observer pattern

We are going to make use of the Observer architectural design pattern which is language agnostic. The Observer pattern offers a subscription model in which objects subscribe to an event and get notified when the event occurs. This pattern is the cornerstone of event-driven programming, including JavaScript. The Observer pattern facilitates good object-oriented design and promotes loose coupling.

Observers are also called Subscribers and we refer to the object being observed as the Publisher (or the subject). Publishers notify subscribers when events occur.

When objects are no longer interested in being notified by the subject they are registered with, they can unsubscribe themselves. The subject will then, in turn, remove them from the observer collection.

Open up the src\js directory, then create a new folder called lib. Inside this folder create a new file called pubsub.js. The structure of your js folder should look like this:

/js
   ├── lib
      ├── pubsub.js

In this file, we are creating the functionality to allow other parts of our application to subscribe to and publish named events.

Enter the following code to pubsub.js

export default class PubSub {
    constructor() {
        this.events = {};
    }
    subscribe(event, callback) {
        if (!this.events.hasOwnProperty(event)) {
            this.events[event] = [];
        }
        return this.events[event].push(callback);
    }
    publish(event, data = {}) {
        if (!this.events.hasOwnProperty(event)) {
            return [];
        }
        return this.events[event].map(callback => callback(data));
    }
}

In the constructor, we are instantiating this.events to an empty object which will hold our events.

The subscribe method accepts a string event, which is the event’s unique name and a callback function. Then it checks if this.events has a matching event among its properties-if the event is not found, it creates the eventproperty as a blank array. Otherwise, it pushes the passed callback method into this.events[event].

The publish method checks if this.events has a matching event among its properties-if the event is not found it returns an empty array. Otherwise, it loops through each stored callback with the data object as an argument.

The store

Next let’s create a central object which will contain a state object that in turn, contains our application state. We will also create a dispatch method which would be called when a user enters a new to-do item. This method calls our action which in turn calls our mutations which finally changes the state.

Create a new folder in your js folder called store. In there, create a new file called store.js so that your folder structure should look like this:

/js
   ├── lib
      ├── pubsub.js
   ├── store
      ├── store.js

Then enter the following into store.js

import PubSub from '../lib/pubsub.js';

export default class Store {
    constructor(params) {
        let self = this;
        self.actions = {};
        self.mutations = {};
        self.state = {};
        self.status = 'default state';
        self.events = new PubSub();
        if (params.hasOwnProperty('actions')) {
            self.actions = params.actions;
        }
        if (params.hasOwnProperty('mutations')) {
            self.mutations = params.mutations;
        }
        self.state = new Proxy((params.state || {}), {
            set: function (state, key, value) {
                state[key] = value;
                console.log(`stateChange: ${key}: ${value}`);
                self.events.publish('stateChange', self.state);
                if (self.status !== 'mutation') {
                    console.warn(`You should use a mutation to set ${key}`);
                }
                self.status = 'resting';
                return true;
            }
        });
    }
    dispatch(actionKey, payload) {
        let self = this;
        if (typeof self.actions[actionKey] !== 'function') {
            console.error(`Action "${actionKey} doesn't exist.`);
            return false;
        }
        console.groupCollapsed(`ACTION: ${actionKey}`);
        self.status = 'action';
        self.actions[actionKey](self, payload);
        console.groupEnd();
        return true;
    }
    commit(mutationKey, payload) {
        let self = this;
        if (typeof self.mutations[mutationKey] !== 'function') {
            console.log(`Mutation "${mutationKey}" doesn't exist`);
            return false;
        }
        self.status = 'mutation';
        let newState = self.mutations[mutationKey](self.state, payload);
        self.state = Object.assign(self.state, newState);
        return true;
    }   
}

Let’s examine what this code is doing. First, we are importing the pubsub.js file. We then declare a constructorwhich accepts an argument. Inside this, we instantiate a default empty objects for stateactions, and mutations. We are also adding a status property that we’ll use to determine what the object is doing at any given time. We then create a new instance of PubSub and assign it to the property events. Then we check if the argument passed into the constructor has the property actions and mutations as it’s own property. If either condition is true, we set the actions and the mutations object to the corresponding parameter of the passed in argument.

Next, we use the new ES6 feature, Proxy to watch the state object. If we add a get trap, we can monitor every time that the object is asked for data. Similarly, with a set trap, we can keep an eye on changes that are made to the object. In our context though, we’re setting the change and then logging it to the console. We’re then publishing a stateChange event with our PubSub module. Then we are checking if status is not a mutation and logging a warning in the console to that effect.

Next, we have the dispatch method which looks for an action and, if it exists, set a status and call the action while creating a login console. The action will then mutate our changes by calling the commit method. In this method, we are checking if a mutation exists, if so we run it and get our new state from its return value. We then take that new state and merge it with our existing state to create an up-to-date version of our state.

Actions and mutations

Now let’s create the action and mutation files which we referred to in the previous section. In your store folder, create a new file called actions.js and add the following to it:

export default {
    addItem(context, payload) {
        context.commit('addItem', payload);
    },
    clearItem(context, payload) {
        context.commit('clearItem', payload);
    }
};

The context, is the instance of the Store class and the payload is the actual data change, passed in by the dispatch method in the Store class. The actions addItem and clearItem is passing the payload to a mutation-the commit method which, in turn, commits the data to store. Let’s now create our mutation. Create a new file, still in the store folder called mutations.js:

export default {
    addItem(state, payload) {
        state.items.push(payload);
        return state;
    },
    clearItem(state, payload) {
        state.items.splice(payload.index, 1);
        return state;
    }
};

As explained previously this mutation is called by the commit method in our action.js file. Here addItem accepts our current state and a payload as an argument, then pushes the payload into an items property of the state object. The second method, clearItem removes the payload passed in from the state object.

Next, let’s create a file which would hold default set of items so that on first-load our application will have something to display. In the same folder, create a file state.js and enter the following:

export default {  
    items: [
        'An example task. Delete or add your own',
        'Another example task. Delete or add your own'
    ]
};

Create another file called index.js in the same directory, in which we will import our actionsmutationsstate and store. Enter the following in this file:

import actions from './actions.js';
import mutations from './mutations.js';
import state from './state.js';
import Store from './store.js';

export default new Store({
  actions,
  mutations,
  state
});

Components

Our application has just three functionalities: show a list of tasks, add tasks and show a count of tasks. We will separate out these functionalities into three component files, but first we will create a base component. Create a file called component.js in the lib folder. So your lib folder structure looks like this:

├── lib
   ├── pubsub.js
   ├── component.js

In the component.js file, enter the following:

import Store from '../store/store.js';
export default class Component {
    constructor(props = {}) {
        this.render = this.render || function () { };
        if (props.store instanceof Store) {
            props.store.events.subscribe('stateChange', () => this.render());
        }
        if (props.hasOwnProperty('element')) {
            this.element = props.element;
        }
    }
}

Here we are importing the Store class which we will use to check one of our properties in the constructor. In the constructor we’re looking to see if we’ve got a render method. If this Component class is the parent of another class, then the child class will have likely set its own method for render. If there is no method set, we create an empty method that will prevent things from breaking.

Next, we check if the passed in object has a property that is an instance of the Store class which we imported. We do this so we can confidently use its methods and properties. Then we call the subscribe method, passing in the name of the event we are subscribing to-the global stateChange event and the callback render. Finally, we get an element property from our child component

Now that we have the parent component, let’s create the child components. First, create a new folder called components inside the js folder. In this folder create a file called list.js. Your js folder structure should look like this:

/js
   ├── lib
   ├── components
      ├── list.js

In the list.js file, enter the following:

import Component from '../lib/component.js';
import store from '../store/index.js';
export default class List extends Component {
    constructor() {
        super({
            store,
            element: document.querySelector('.js-items')
        });
    }
    render() {
        
        if (store.state.items.length === 0) {
            this.element.innerHTML = `<p class="no-items">You have no tasks yet </p>`;
            return;
        }
        this.element.innerHTML = `
      <ul class="app__items">
        ${store.state.items.map(item => {
            return `
            <li>${item}<button aria-label="Delete this item">×</button></li>
          `
        }).join('')}
      </ul>
    `;
        this.element.querySelectorAll('button').forEach((button, index) => {
            button.addEventListener('click', () => {
                store.dispatch('clearItem', { index });
            });
        });
    }
};

Here in the constructor, we are using the super keyword to access and call functions on our parent’s component, that is the components.js file. We start off by passing our Store instance up to the parent class that we are extending.

After that, we declare a render method that gets called each time the stateChange event happens. This is also the method the parent component.js checks for. In this render method we put out either a list of items or a little notice if there are no items. You’ll also see that each button has an event attached to it and they dispatch and action within our store.

Next, let’s create the count component. Create a new file called count.js in the same folder and enter the following:

import Component from '../lib/component.js';
import store from '../store/index.js';
export default class Count extends Component {
    constructor() {
        super({
            store,
            element: document.querySelector('.js-count')
        });
    }
    render() {
        let suffix = store.state.items.length !== 1 ? 's' : '';
        this.element.innerHTML = `
      <small>You have</small>
      ${store.state.items.length}
      <small>task${suffix} today </small>
    `;
    }
}

This handles the count of our items and it is self-explanatory. Let’s move on to the last component. Create a new file called status.js and enter the following:

import Component from '../lib/component.js';
import store from '../store/index.js';
export default class Status extends Component {
    constructor() {
        super({
            store,
            element: document.querySelector('.js-status')
        });
    }
}

Views

The last thing we need to do is to create a main.js file and the index.html view. In the js folder create the main.js file and enter the following:

import store from './store/index.js';
import Count from './components/count.js';
import List from './components/list.js';
import Status from './components/status.js';
const formElement = document.querySelector('.js-form');
const inputElement = document.querySelector('#new-item-field');
formElement.addEventListener('submit', evt => {
    evt.preventDefault();
    let value = inputElement.value.trim();
    if (value.length) {
        store.dispatch('addItem', value);
        inputElement.value = '';
        inputElement.focus();
    }
});
const countInstance = new Count();
const listInstance = new List();
const statusInstance = new Status();
countInstance.render();
listInstance.render();
statusInstance.render();

Here all we’re doing is pulling in dependencies that we need. We’ve got our Store, our front-end components and a couple of DOM elements to work with. Next, we are adding an event listener to the form and preventing it from submitting using preventDefault. We then grab the value of the textbox and trim any whitespace off it. We do this because we want to check if there’s actually any content to pass to the store next. Finally, if there’s content, we dispatch our addItem action with that content

Then we are creating new instances of our components and calling each of their render methods so that we get our initial state on the page.

In the src folder create the index.html file, and enter the following code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <link rel="stylesheet" href="css/global.css" />
    <link rel="stylesheet" href="https://bootswatch.com/4/flatly/bootstrap.css" />
    <title>Todo</title>
</head>
<body>
    <main>
        <header class="intro">
            <h1 class="intro__heading">Todo List</h1>
        </header>
        <section class="app">
            <section class="app__input">
                <h2 class="app__heading">Tasks</h2>
                <div class="js-items" aria-live="polite" aria-label="A list of items you have to done"></div>
                <form class="new-item js-form ">
                  <div>
                    <input type="text" class="new-todo" id="new-item-field" autocomplete="off" placeholder="What is to be done"/>
                    <button class="btn-primary save-button">Save</button>
                  </div>
                </form>
        </section>
          <aside class="app__status">
            <p role="status" class="visually-hidden"><span class="js-status"></span></p>
              <div class="app__decor js-count" aria-hidden="true">
              </div>
          </aside>
        </section>
    </main>
    <script type="module" src="js/main.js"></script>
</body>
</html>

LocalStorage

Using terminal, cd into the src folder and run the command http-server. This will serve our application in a local web server. Now visit the URL http://localhost:8080 to view the application. Go ahead and add something like “Read book” in there.

You will notice that when we refresh the page, the data we entered is lost. We need a way to persist or store the data we entered. LocalStorage lets us store data in the browser, which can be retrieved even when the user closes or reloads the page. We also have the ability to write, update and delete data from localStorage. We can get item using the method localStorage.getItem, set item using the method localStorage.setItem and remove item using the method localStorage.removeItem.

Let’s setup localStorage in our application. In the /src/js/store/mutations.js file, replace the content with:

export default {
    addItem(state, payload) {
        state.items.push(payload);
        localStorage.setItem('items', JSON.stringify(state.items))   
        return state;
    },
    clearItem(state, payload) {
        state.items.splice(payload.index, 1);
        localStorage.setItem('items', JSON.stringify(state.items))
        return state;
    }
};

In the addItem method, after pushing the payload into the state object, we are converting state.items into a string and storing it in localStorage with key name items. We are doing a similar same thing in the clearItemmethod, hereafter removing an item from state.items, we are updating localStorage with the updated value of state.items.

Next in /src/js/store/state.js, replace its content with:

export default {
    items: JSON.parse(localStorage.getItem('items') || '[]')   
};

Here we are checking localStorage if a key named items exists. If it does, we want to set it to the variable itemsotherwise set items to an empty array. Now our application can retain the data we entered even when we reload or close the page.

For those more advanced

If you recall in the store.js file, we made use of an ES6 feature, Proxy to monitor the state object. What this essentially does is wraps an existing object, also known as the target and intercept any access to its attributes or methods even if they do not exist. The proxy object has some traps, that can be called before granting access to the target. Here we are using the set trap to keep an eye on changes that are made to the state object. That means that when a mutation runs something like state.name ="Foo" , this trap catches it before it can be set. Some use cases for proxies include validation, value correction, property lookup extensions, tracing property accesses and many more.

Conclusion

We have explored how to implement state management in JavaScript. In the process, we have learned about the Observer architectural design pattern and localStorage. There are many scenarios where you will need to implement state management, one of which is user management and authentication. You can look at the final product on Githuband if you have any questions or comments, don’t hesitate to post them below.

Originally published by. Caleb Oki at https://blog.logrocket.com

Learn more

☞ Node.js / Javascript performance coding tips to make applications faster

☞ JavaScript Modules: From IIFEs to CommonJS to ES6 Modules

☞ Visual Studio Code Settings and Extensions for Faster JavaScript Development

☞ The Complete JavaScript Course 2019: Build Real Projects!

☞ Become a JavaScript developer - Learn (React, Node,Angular)

☞ JavaScript: Understanding the Weird Parts

☞ Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)

☞ The Full JavaScript & ES6 Tutorial - (including ES7 & React)

☞ JavaScript - Step By Step Guide For Beginners

JavaScript Tutorial: if-else Statement in JavaScript

JavaScript Tutorial: if-else Statement in JavaScript

This JavaScript tutorial is a step by step guide on JavaScript If Else Statements. Learn how to use If Else in javascript and also JavaScript If Else Statements. if-else Statement in JavaScript. JavaScript's conditional statements: if; if-else; nested-if; if-else-if. These statements allow you to control the flow of your program's execution based upon conditions known only during run time.

Decision Making in programming is similar to decision making in real life. In programming also we face some situations where we want a certain block of code to be executed when some condition is fulfilled.
A programming language uses control statements to control the flow of execution of the program based on certain conditions. These are used to cause the flow of execution to advance and branch based on changes to the state of a program.

JavaScript’s conditional statements:

  • if
  • if-else
  • nested-if
  • if-else-if

These statements allow you to control the flow of your program’s execution based upon conditions known only during run time.

  • if: if statement is the most simple decision making statement. It is used to decide whether a certain statement or block of statements will be executed or not i.e if a certain condition is true then a block of statement is executed otherwise not.
    Syntax:
if(condition) 
{
   // Statements to execute if
   // condition is true
}

Here, condition after evaluation will be either true or false. if statement accepts boolean values – if the value is true then it will execute the block of statements under it.
If we do not provide the curly braces ‘{‘ and ‘}’ after if( condition ) then by default if statement will consider the immediate one statement to be inside its block. For example,

if(condition)
   statement1;
   statement2;

// Here if the condition is true, if block 
// will consider only statement1 to be inside 
// its block.

Flow chart:

Example:

<script type = "text/javaScript"> 

// JavaScript program to illustrate If statement 

var i = 10; 

if (i > 15) 
document.write("10 is less than 15"); 

// This statement will be executed 
// as if considers one statement by default 
document.write("I am Not in if"); 

< /script> 

Output:

I am Not in if
  • if-else: The if statement alone tells us that if a condition is true it will execute a block of statements and if the condition is false it won’t. But what if we want to do something else if the condition is false. Here comes the else statement. We can use the else statement with if statement to execute a block of code when the condition is false.
    Syntax:
if (condition)
{
    // Executes this block if
    // condition is true
}
else
{
    // Executes this block if
    // condition is false
}


Example:

<script type = "text/javaScript"> 

// JavaScript program to illustrate If-else statement 

var i = 10; 

if (i < 15) 
document.write("10 is less than 15"); 
else
document.write("I am Not in if"); 

< /script> 

Output:

i is smaller than 15
  • nested-if A nested if is an if statement that is the target of another if or else. Nested if statements means an if statement inside an if statement. Yes, JavaScript allows us to nest if statements within if statements. i.e, we can place an if statement inside another if statement.
    Syntax:
if (condition1) 
{
   // Executes when condition1 is true
   if (condition2) 
   {
      // Executes when condition2 is true
   }
}

Example:

<script type = "text/javaScript"> 

// JavaScript program to illustrate nested-if statement 

var i = 10; 

if (i == 10) { 

// First if statement 
if (i < 15) 
	document.write("i is smaller than 15"); 

// Nested - if statement 
// Will only be executed if statement above 
// it is true 
if (i < 12) 
	document.write("i is smaller than 12 too"); 
else
	document.write("i is greater than 15"); 
} 
< /script> 

Output:

i is smaller than 15
i is smaller than 12 too
  • if-else-if ladder Here, a user can decide among multiple options.The if statements are executed from the top down. As soon as one of the conditions controlling the if is true, the statement associated with that if is executed, and the rest of the ladder is bypassed. If none of the conditions is true, then the final else statement will be executed.
if (condition)
    statement;
else if (condition)
    statement;
.
.
else
    statement;


Example:

<script type = "text/javaScript"> 
// JavaScript program to illustrate nested-if statement 

var i = 20; 

if (i == 10) 
document.wrte("i is 10"); 
else if (i == 15) 
document.wrte("i is 15"); 
else if (i == 20) 
document.wrte("i is 20"); 
else
document.wrte("i is not present"); 
< /script> 

Output:

i is 20

How to Retrieve full Profile of LinkedIn User using Javascript

How to Retrieve full Profile of LinkedIn User using Javascript

I am trying to retrieve the full profile (especially job history and educational qualifications) of a linkedin user via the Javascript (Fetch LinkedIn Data Using JavaScript)

Here we are fetching LinkedIn data like Username, Email and other fields using JavaScript SDK.

Here we have 2 workarounds.

  1. Configuration of linkedIn developer api
  2. Javascript Code to fetch records

Configuration of linkedIn developer api

In order to fetch records, first we need to create developer api in linkedin which will act as token/identity while fetching data from other linkedin accounts.

So to create api, navigate to https://linkedin.com/developer/apps and click on 'Create Application'.

After navigating, fill in details like name, description and other required fields and then submit.

As we submit, it will create Client ID and Client Secret shown below, which we will be using in our code while communicating to fetch records from other LinkedIn account.

Note: We need to provide localhost Url here under Oauth 2.0. I am using my localhost, but you can probably use other production URLs under Oauth 2.0 where your app is configured. It will make your api  consider the Url as trusted which fetching records.

Javascript Code to fetch records

For getting user details like first name, last name,User image can be written as,

<script type="text/javascript" src="https://platform.linkedin.com/in.js">  
    api_key: XXXXXXX //Client ID  
    onLoad: OnLinkedInFrameworkLoad //Method that will be called on page load  
    authorize: true  
</script>  
<script type="text/javascript">  
    function OnLinkedInFrameworkLoad() {  
        IN.Event.on(IN, "auth", OnLinkedInAuth);  
    }  
  
    function OnLinkedInAuth() {  
        IN.API.Profile("me").result(ShowProfileData);  
    }  
  
    function ShowProfileData(profiles) {  
        var member = profiles.values[0];  
        var id = member.id;  
        var firstName = member.firstName;  
        var lastName = member.lastName;  
        var photo = member.pictureUrl;  
        var headline = member.headline;  
        //use information captured above  
        var stringToBind = "<p>First Name: " + firstName + " <p/><p> Last Name: " + lastName + "<p/><p>User ID: " + id + " and Head Line Provided: " + headline + "<p/>"  
        document.getElementById('profiles').innerHTML = stringToBind;  
    }  
</script>    

Kindly note we need to include 'https://platform.linkedin.com/in.js' as src under script type as it will act on this Javascript SDK provided by Linkedin.

In the same way we can also fetch records of any organization with the companyid as keyword.

<head>  
    <script type="text/javascript" src="https://platform.linkedin.com/in.js">  
        api_key: XXXXXXX ////Client ID  
        onLoad: onLinkedInLoad  
        authorize: true  
    </script>  
</head>  
  
<body>  
    <div id="displayUpdates"></div>  
    <script type="text/javascript">  
        function onLinkedInLoad() {  
            IN.Event.on(IN, "auth", onLinkedInAuth);  
            console.log("On auth");  
        }  
  
        function onLinkedInAuth() {  
            var cpnyID = XXXXX; //the Company ID for which we want updates  
            IN.API.Raw("/companies/" + cpnyID + "/updates?event-type=status-update&start=0&count=10&format=json").result(displayCompanyUpdates);  
            console.log("After auth");  
        }  
  
        function displayCompanyUpdates(result) {  
            var div = document.getElementById("displayUpdates");  
            var el = "<ul>";  
            var resValues = result.values;  
            for (var i in resValues) {  
                var share = resValues[i].updateContent.companyStatusUpdate.share;  
                var isContent = share.content;  
                var isTitled = isContent,  
                    isLinked = isContent,  
                    isDescription = isContent,  
                    isThumbnail = isContent,  
                    isComment = isContent;  
                if (isTitled) {  
                    var title = isContent.title;  
                } else {  
                    var title = "News headline";  
                }  
                var comment = share.comment;  
                if (isLinked) {  
                    var link = isContent.shortenedUrl;  
                } else {  
                    var link = "#";  
                }  
                if (isDescription) {  
                    var description = isContent.description;  
                } else {  
                    var description = "No description";  
                }  
                /* 
                if (isThumbnailz) { 
                var thumbnailUrl = isContent.thumbnailUrl; 
                } else { 
                var thumbnailUrl = "http://placehold.it/60x60"; 
                } 
                */  
                if (share) {  
                    var content = "<a target='_blank' href=" + link + ">" + comment + "</a><br>";  
                    //el += "<li><img src='" + thumbnailUrl + "' alt=''>" + content + "</li>";  
                    el += "<li><div>" + content + "</div></li>";  
                }  
                console.log(share);  
            }  
            el += "</ul>";  
            document.getElementById("displayUpdates").innerHTML = el;  
        }  
    </script>  
</body>  

We can get multiple metadata while fetching records for any any organization. We can get company updates as shown below.

Conclusion

We can also fetch any company specific data like company job updates/post, total likes, comments, and number of views along with a lot of metadata we can fetch which I have shown below.

Thank you for reading !

7 Best Javascript Iframe Libraries

7 Best Javascript Iframe Libraries

Iframes let you build user experiences into embeddable ‘cross-domain components’, which let users interact with other sites without being redirected. I have compiled 7 best Javascript iframe libraries.

Iframes let you build user experiences into embeddable ‘cross-domain components’, which let users interact with other sites without being redirected. I have compiled 7 best Javascript iframe libraries.

1. Zoid

A cross-domain component toolkit, supporting:

  • Render an iframe or popup on a different domain, and pass down props, including objects and functions
  • Call callbacks natively from the child window without worrying about post-messaging or cross-domain restrictions
  • Create and expose components to share functionality from your site to others!
  • Render your component directly as a React, Vue or Angular component!
    It's 'data-down, actions up' style components, but 100% cross-domain using iframes and popups!

Download


2. Postmate

Postmate is a promise-based API built on postMessage. It allows a parent page to speak with a child iFrame across origins with minimal effort.

Download


3. Iframe Resizer

Keep same and cross domain iFrames sized to their content with support for window/content resizing, in page links, nesting and multiple iFrames

Demo

Download


4. Iframely

Embed proxy. Supports over 1800 domains via custom parsers, oEmbed, Twitter Cards and Open Graph

Demo

Download


5. React Frame component

This component allows you to encapsulate your entire React application or per component in an iFrame.

Demo

Download


6. Seamless.js

A seamless iframe makes it so that visitors are unable to distinguish between content within the iframe and content beside the iframe. Seamless.js is a JavaScript library (with no dependencies) that makes working with iframes easy by doing all the seamless stuff for you automatically.

Demo

Download


7. Porthole

A proxy to safely communicate to cross-domain iframes in javascript

Demo

Download


Thank for read!