LWC: Display Latest News using API

In this post we are going to see how to show latest news fetched from API in salesforce Lightning Web Components.

Key Features:

1)I have used free source api (REST Service) to get the latest news.

2)On click of article link/image, new tab will be opened showing the full article.

3)We can also change country and category of news.

  • First you need to login and subscribe to the Basic plan(no charges) in NewAPI website to get the api details.Click here to register
  • Once you subscribed to the basic plan we will get the "key",using this we will hit the service to get the latest news.
  • We need to use "GET" method and use the end point url with key which we got from the NewsAPI site.
  • Below is the endpoint url I am going to use.
  "http://newsapi.org/v2/top-headlines?country=in&apiKey=yourapikey"

  • Now url is ready,write a apex class to fetch the data and deserialize the json to custom list.


getLatestNewsClass.apxc

  • public class getLatestNewsClass {
    @AuraEnabled
    public articleList[] articles;
    public class articleList{
    @AuraEnabled
    public string author;
    @AuraEnabled
    public string title;
    @AuraEnabled
    public string description;
    @AuraEnabled
    public string url;
    @AuraEnabled
    public string urlToImage;
    @AuraEnabled
    public Source source;
    }
    public class Source{
    @AuraEnabled
    public string name;
    }
    @AuraEnabled
    public static getLatestNewsClass fetchLatestNewsCallout(){
    Http http = new Http();
    HttpRequest request = new HttpRequest();
    request.setEndpoint('http://newsapi.org/v2/top-headlines?country=in&apiKey=yourkey');
    request.setMethod('GET');
    HttpResponse response = http.send(request);
    if (response.getStatusCode() == 200) {
    system.debug('response==>' + response.getBody());
    string responseData = response.getBody();
    JSONParser parser = JSON.createParser(responseData);
    return (getLatestNewsClass) System.JSON.deserialize(responseData, getLatestNewsClass.class);
    }
    else{
    string responseData = response.getBody();
    return (getLatestNewsClass) System.JSON.deserialize(responseData, getLatestNewsClass.class);
    }
    }
    }
    Create a New Lightning Web Component to show the news fetched from api.We will have two  components here Parent(getLatestNewsLWC) and Child(newsTileComponent).
  • In connectedCallback method I am calling apex class to fetch the data.
  • In Parent component I am using template:iteration to iterate all the articles and passing each article to the child component.

getLatestNewsLWC.html    
<template>
<lightning-card title="Latest News">
<div class="slds-scrollable_y" style="height:250px;">
<lightning-layout multiple-rows horizontal-align="center">
<template for:each={newsList} for:item="newsRecord">
<lightning-layout-item key={newsRecord.title} padding="around-small" size="3">
<c-news-tile-component news-rec={newsRecord}></c-news-tile-component>
</lightning-layout-item>
</template>
</lightning-layout>
</div>
</lightning-card>
</template>
  

getLatestNewsLWC.js  

  • import { LightningElement } from 'lwc';
    import getNews from '@salesforce/apex/getLatestNewsClass.fetchLatestNewsCallout';
    export default class GetLatestNesLWC extends LightningElement {
    newsList;
    errorMsg;
    connectedCallback(){
    getNews({})
    .then(result => {
    this.newsList = result.articles;
    })
    .catch(error => {
    this.errorMsg = error;
    });
    }
    }
    In Child component we get the article data from the parent component and show the articles in list.

newsTileComponent.html 

<template>
<a onclick={openSelectedArticle}>
<img src={newsRec.urlToImage} class="newsRecord slds-align_absolute-center" alt="Image" >
</br><p class="title slds-align_absolute-center">
{newsRec.title}
</p>
</a>
</template>
newsTileComponent.js

import { LightningElement,api } from 'lwc';
export default class NewsTileComponent extends LightningElement {
@api newsRec;
openSelectedArticle(event){
event.preventDefault();
const selectedArticle = this.newsRec.url;
window.open(selectedArticle,"_blank");
}
}
newsTileComponent.css

img.newsRecord {
height: 120px;
max-width: initial;
pointer-events: none;
}

Comments

Post a Comment