Hoppe’s Debuts “How to Clean” Gun-Cleaning Video Series

Hoppe’s Debuts “How to Clean” Gun-Cleaning Video Series

https://ift.tt/2BiKVWw

Hoppe's 9
Hoppe’s is more than just excellent cologne, it’s also a great gun cleaner. IMG Hoppe’s

U.S.A. -(AmmoLand.com)- Hoppe’s, the No.1 name in gun care products, announced today that it has added another new video to its popular “How to Clean” Series, which provides step-by-step cleaning instructions on some of today’s most popularly owned firearms. The 15-part video series is available for viewing on the Hoppe’s website, YouTube, and Facebook pages.

Developed to provide effective, yet easy-to-follow cleaning instructions for a variety of different firearms, the Hoppe’s video series is the perfect resource for first-time gun owners. The “How to Clean” series also serves as a valuable refresher course for any firearms enthusiast. Throughout the series, host Luke Williams, better known as Outdoors By Luke, provides simple and important tips on cleaning a myriad of firearms ranging from the popular Glock 17 pistol to the Ruger 10-22.

“As the industry welcomes more first time firearms owners than ever before, the need to provide helpful cleaning instructions has never been greater,” said Eliza Graves, Sr. Brand Manager for Hoppe’s. “Through our instructional video series, longtime and novice gun owners alike can easily find helpful tips that will keep their firearms running like new.”

To view the Hoppe’s new “How to Clean” series and to see the company’s full line of gun care products and accessories, be sure to visit www.hoppes.com


Hoppe's logoAbout Hoppe’s

In 1903, Frank August Hoppe mixed nine chemicals and created the world’s most effective gun cleaner. As a well-trained young soldier, Frank knew that gun care went far beyond just a clean rifle, but actually helped to ensure his safety while on the front lines of battle. Since that time, Hoppe’s has emerged as the leading gun care company, having grown along-side hunters, shooters, and soldiers who depend on their firearms every day. It has remained the most trusted name in gun care by advancing and evolving technologies to meet those needs. From the ever-popular and versatile No. 9 and the quick and easy BoreSnake, to the marvel of efficiency we call Gun Medic, Hoppe’s is the only name you need to know for firearm cleaning and protection.

The post Hoppe’s Debuts “How to Clean” Gun-Cleaning Video Series appeared first on AmmoLand.com.

guns

via AmmoLand.com https://ift.tt/2okaFKE

June 17, 2020 at 10:55AM

Laravel Intellisense Plugin for Visual Studio Code

Laravel Intellisense Plugin for Visual Studio Code

https://ift.tt/37pDYiy

Laravel Intellisense is a Visual Studio Code plugin by Mohamed Benhida that provides some nice auto-completion for things like Eloquent models, factories, config, and API resources.

The thing I appreciate about this plugin is support for things like config(), view(), and other areas of Laravel you’d typically not have auto-completion for in most editors, but could save a decent amount of time context switching between the database and code.

Here’s the full list of features:

  • Resource Autocompletion
  • Eloquent Autocompletion
  • Factory Autocompletion
  • View Autocompletion
  • Config Autocompletion
  • Route Autocompletion

What’s nice about this plugin is that it provides help for things unique to Laravel developers: editor help around your model data. The plugin provides auto-completion by using an app’s database connection to get model attributes.

For example, let’s say you need to write a factory for a newly created model. With the current version of Laravel, you need to reference database fields in a migration class, a database table, or perhaps a PHPDoc field names to see what’s available.

If Visual Studio Code isn’t for you, Blueprint might mitigate some of the need for this auto-completion by generating various files from a centralized configuration file. You could also benefit from using both Blueprint and Laravel Intellisense together, I just want to point out that there are multiple ways to manage the mundane parts of files and code around application data.

Another solution might be the Laravel Populated Factory plugin, but that only helps with factories.

I typically manage a list of @property-read values in the model class documentation (which serves as a helpful reference and auto-completion for model attributes), but that doesn’t help with auto-completion when trying to fill out factory array keys.

The View completion is another added benefit that allows you to avoid manually looking up files as often:

PhpStorm doesn’t provide auto-complete using the helper function, however, it does support auto-complete with the @include directive within Blade files.

Learn More

You can download this plugin by visiting laravel intellisense in the Visual Studio Marketplace. The source code is available on GitHub at simoebenhida/laravel-intellisense.

Filed in:
News
/
Editors
/
vscode

programming

via Laravel News https://ift.tt/14pzU0d

June 12, 2020 at 09:08AM

How To Mount and Zero a Rifle Scope (With a Free Printable Target)

How To Mount and Zero a Rifle Scope (With a Free Printable Target)

https://ift.tt/3f6u6N7

By Kevin Wabiszewski You’re ready to throw that new glass on your rifle and see what damage you can do from afar. First, you’ll have to zero that scope. If you’ve never done that before, it’s important to learn exactly how to perform and replicate the process so that you can swap out future scopes […]

The post How To Mount and Zero a Rifle Scope (With a Free Printable Target) appeared first on The Truth About Guns.

guns

via The Truth About Guns https://ift.tt/1TozHfp

June 9, 2020 at 05:06PM

Detect AdBlocker With Javascript And Increase Website Ads Revenue

Detect AdBlocker With Javascript And Increase Website Ads Revenue

https://ift.tt/2YgQzjX

Hello fellas! In this article, I will show you how to detect if the browser has AdBlocker plugins enabled. If it’s enabled then how to request your website visitors not to block ads and increase your Ads Revenue.

Code is available in GitHub @ Detect AdBlocker

We will cover

  1. Don’t Add Too Many Ads In Between Content
  2. Don’t Block Whole Website Until They Disable AdBlock
  3. Implementing With Example

Prerequisites

Very basic knowledge of HTML & Javascript.


1) Don’t Add Too Many Ads In Between Content

Adding Ads might be the main income for you to run website, I totally understand. But keep in mind not to add too much Ads in between the content it might be very distracting or piss of your viewers.

Your content might be great but you will loose viewers who constantly come to your website.


2) Don’t Block Whole Website Until They Disable AdBlock

I have seen couple of websites where they totally block the content till the user doesn’t disable the ads which is totally not a good idea for website owners. I know I can feel your pain, but as wisely said “customer is the king” .

Instead you can show some alert text for your viewers to disable the ads. Believe me at least 80% of them will definitely support you if you really have good content for them 🙂


3) Implementing With Example

Oh! Boy enough blabbering. Lets get start with implementation.

Following is the project folder structure:

index.html
assets/
    js/
        blockadblock.js 
        checkads.js 

index.html – Here we will add normal content along with alert text when viewer uses adblocker

blockadblock.js (Not Required If We Use CDN link) – Its just the library file which is included locally as I use cache in my website. So need to pull too many times. Even we can use CDN over here to avoid including this file.

checkads.js – In this file we will detect the adblocker. Surely we can add it in index.html file but as your project increases it will be bit cumbersome to mange it.

Javascript Library Used

We are using FuckAdblock javascript library for implementation

CDN Usage

<script src="https://cdnjs.cloudflare.com/ajax/libs/fuckadblock/3.2.1/fuckadblock.min.js" integrity="sha256-3zU5Lr4nIt3K/BgGOQMduajtZcPV9elIM/23RDXRp3o=" crossorigin="anonymous"></script>

If the above script doesn’t work for you then please use this URL to get the new script tag Fuck AdBlock.

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AdBlocker Demo</title>


    <style>
        #adblock-alert{ display: none; }
        #adblock-alert .alert{ padding: 20px; background: red; border-radius: 4px; colour: #fff; }
    </style>
</head>
<body>
    <div id="adblock-alert">
        <div class="alert">
            Good content takes time and effort to come up with. <br><br>
            Please consider supporting us by just disabling your <strong>AD BLOCKER</strong> and reloading this page again.
        </div>
    </div>
    <p>This is simple page.</p>

    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/fuckadblock/3.2.1/fuckadblock.min.js" integrity="sha256-3zU5Lr4nIt3K/BgGOQMduajtZcPV9elIM/23RDXRp3o=" crossorigin="anonymous"></script>

    
    <script src="./assets/js/checkads.js"></script>
</body>
</html>

We need to display adblock alert only when adblocker is detected. Hence hide the adblock alert content using display:none CSS.

Observe the following javascript code in above index.html file.

CDN Library

<script src="https://cdnjs.cloudflare.com/ajax/libs/fuckadblock/3.2.1/fuckadblock.min.js" integrity="sha256-3zU5Lr4nIt3K/BgGOQMduajtZcPV9elIM/23RDXRp3o=" crossorigin="anonymous"></script>


<script src="./assets/js/checkads.js"></script>

checkads.js

function adBlockNotDetected() {
    var adContent = document.getElementById('adblock-alert');
    adContent.style.display = 'none';
}



function adBlockDetected() {
    var adContent = document.getElementById('adblock-alert');
    adContent.style.display = 'block';
}



if(typeof fuckAdBlock !== 'undefined' || typeof FuckAdBlock !== 'undefined') {
    
    
    adBlockDetected();
} else {
    
    var importFAB = document.createElement('script');
    importFAB.onload = function() {
        
        fuckAdBlock.onDetected(adBlockDetected)
        fuckAdBlock.onNotDetected(adBlockNotDetected);
    };
    importFAB.onerror = function() {
        
        
        adBlockDetected(); 
    };
    importFAB.integrity = 'sha256-xjwKUY/NgkPjZZBOtOxRYtK20GaqTwUCf7WYCJ1z69w=';
    importFAB.crossOrigin = 'anonymous';
    importFAB.src = 'https://cdnjs.cloudflare.com/ajax/libs/fuckadblock/3.2.1/fuckadblock.min.js';
    document.head.appendChild(importFAB);
}

We are enabling or disabling the adblock alert text with the following functions. You will be able to see it in the above code

function adBlockNotDetected() {
    var adContent = document.getElementById('adblock-alert');
    adContent.style.display = 'none';
}



function adBlockDetected() {
    var adContent = document.getElementById('adblock-alert');
    adContent.style.display = 'block';
}

Using blockadblock.js Instead Of CDN

Copy and paste this URL FuckAdblock in your browser. It will show the minified code, copy and paste this code in blockadblock.js file. Once you add it you need to include in your index.html file as follows

<script src="./assets/js/blockadblock.js"></script>


<script src="./assets/js/checkads.js"></script>

NOTE: Once you disable your adblock make sure to reload the page. Else the changes made wont take affect

The following is how your website looks when adblock is detected

When AdBlocker Is Detected In Browser

When AdBlocker Is Detected In Browser

The following is how your website looks when adblock is not detected

When AdBlock Is Paused And Page Reloaded

When AdBlock Is Paused And Page Reloaded


Conclusion

Hope you liked the article. Please share with your friends and keep following 🙂

Code is available in GitHub @ Detect AdBlocker

WHATS NEXT?

You might be interest to learn more on composer please find my whole article on it

Upload File From Frontend Server {GuzzleHttp} To REST API Server In PHP {Laravel}

Simple Way To Create Resourceful API Controller In Laravel

Move Uploaded Files From Local Computer Or Server To Amazon S3 Bucket In PHP

Why And How To Use PHP PDO With CRUD Examples

What Is Method Chaining In PHP?

Send Email In PHP With PHPMailer

How To Upload Multiple Files In PHP?

Proper Way To Validate MIME Type Of Files While Handling File Uploads In PHP

Happy Coding 🙂

programming

via Laravel News Links https://ift.tt/2dvygAJ

June 9, 2020 at 11:42AM

Data SRE – Building Database Systems Infrastructure for Performance and Reliability

Data SRE – Building Database Systems Infrastructure for Performance and Reliability

https://ift.tt/2AcYYwC

Data SRE – Building Database Systems Infrastructure Operations for Performance and Reliability


Recently ( on Friday, 5 June 2020 – 06:00 PM PDT to 06:45 PM PDT  ) our Founder and Principal ( Shiv Iyer ) did a webinar on building Database Systems Infrastructure Operations for Performance and Reliability. In this webinar, he discussed about capacity planning / sizing, observability & resilience, performance audit / health-check / diagnostics / forensics, performance optimization & tuning and building highly available / fault-tolerant / self-healing systems architecture. You can download the PDF of the webinar here . Thanks for joining the webinar and making it a success, Looking forward to seeing you all in the next webinar.

 

The post Data SRE – Building Database Systems Infrastructure for Performance and Reliability appeared first on The WebScale Database Infrastructure Operations Experts.

technology

via Planet MySQL https://ift.tt/2iO8Ob8

June 7, 2020 at 12:25AM

A new item to add to your EDC

A new item to add to your EDC

https://ift.tt/37eit47

I purchased one of these in 12 inches, the ASP Protector concealable baton.

It is about the same size as a tactical flashlight the uses two CR123 batteries (Surefire 6P, Streamlight ProTac, etc), just under one inch in diameter and five inches long.

Clipping it into a pocket you’d think it was just a tactical flashlight.

In these uncertain times, it is a tool to fit between nothing and a gun.

You need to check your state laws to see if it legal in your area.  Alabama doesn’t care.  It is legal in Florida with a CWP (in Florida it is a Concealed Weapons Permit, so it’s good for more than just guns).

If it is legal in your state, I think it is a tool worth the $45 I found it for online.

Stay safe out there.

 

 

guns

via https://gunfreezone.net

June 6, 2020 at 08:30PM

And what after police has been banned? This!

And what after police has been banned? This!

https://ift.tt/2UhN0sy

I’m not gonna lie, this isn’t exactly what I expected — lying here in the hospital. I mean, it’s only a few broken bones, a punctured lung, and some stitches to the head, but I almost feel betrayed. Three weeks ago when I took the five-hour online course to become an unarmed rapid response social worker, I thought I was helping mankind. After all, with the police abolished, somebody had to be there to mitigate when people had inevitable disagreements.

I’m The Rapid Response Social Worker Who Replaced The Police

This is a hilarious and possibly prophetic article of what could happen if the Police Defunding/elimination were to happen.  Go rad the whole thing.

Another option I have seen bounced around is the elimination of qualified immunity and substitute it by some sort of insurance. I think this is even funnier and the unintended consequences would be just poetic. First, cops would not be able t pay the full premiums that insurance companies will ask. That means the force and the local government will have to step in and help out, just like it was Health Insurance. Group Legal and Liability Insurance for Local PD department will be established and premiums will go up an down for certain individuals depending on risk  just like in health insurance. A desk Sargent that never come out the precinct will have a low premium.  Billy Bob Doing Traffic control and Highway DUI patrols will pay like he was smoking 4 packs a day while taking X-rays unprotected.

And then, the first year will come around, the White Shirts will sit down with the insurance people and probably a conversation like this will occur.

“Thank you for seeing us, Chief. We need to address some issues with your coverage.”
“What issues?”
“Well, we checked the stats and we need to see how we drop some of the risks or unfortunately we will have to drop your coverage or raise the premiums at least 80%.”
“My God! We cannot afford that! Taxpayers are already pissed off that the county raised taxes to pay for the insurance.”
“I can certainly understand your problem. (pulls out a map of the city) So we had our people examine the data provided by your department and we found out that most of the complains and lawsuit originate in these two areas of town shaded in red. They are responsible for 71% of all the lawsuits and payments we had to issue.”
“Yes, these are troublesome spots. What do you propose?”
“Simply to stop sending officers there. No more patrols means no more contact between officers and probable plaintiffs there fore no lawsuits and no more payments to be made.”
“Are you crazy? The press would crucify us!”
“The press ain’t paying your policy. Taxpayers are.”
“And you understand the Mayor will raise hell. A lot of his voters live there.”
“That is politics which we are not interested in discuss. nor it is our purview.”
“Hmmm. It can be sold if the proper focus is given. These areas have made clear that they do not want cops. We can grant them their wish and we can continue to have coverage.”
“Again chief, that is politics and we don’t get involved on that stuff. we just shown you what we found and how much is going to cost you or not depending on how your department will adjust.”
“I understand. I want to thank you and I am sure we will continue to do business.”

Just saying…

guns

via https://gunfreezone.net

June 6, 2020 at 09:30AM

How to Use SketchUp for 3D Design

How to Use SketchUp for 3D Design

https://ift.tt/3eNuBf1

howto-sketchup

Sometimes you need to describe a building in a way that can’t easily be explained in writing. Often, these structures are of the 3D variety, such as architectural models or interior design.

If you’re already familiar with 3D modeling, then you’ll definitely be aware of this more “descriptive” need. However, what if you’re just a hobbyist who wants to create 3D objects for fun? If you fall under this category, you can try SketchUp. While SketchUp does have a paid version of its app, there is a free web version for casual enthusiasts, too.

In this article, we explain what SketchUp is, what the free version offers, and how to use SketchUp if you’re brand new to the program. This is 3D modelling for everyone, including absolute beginners.

What Is SketchUp?

Trimble SketchUp

SketchUp, formerly Google SketchUp, is a 3D modeling program that was released in the year 2000. It is now owned by a company called Trimble.

As a program that is devoted to 3D modeling, SketchUp is perfect for a wide range of uses. These uses vary, from architectural design and landscaping to film and game development. With pre-fab models that you can use in your designs, this app also acts as a collective engine where you can easily build 3D structures and render them.

The History of SketchUp

The story behind SketchUp is really cool, in that it was originally designed by @Last Software. SketchUp was acquired by Google in 2006, before being passed off to Trimble in 2012.

The company behind this app designed it with the expressed purpose of creating a program that was simple to use. This simplicity was much needed, as 3D modeling programs usually have a steep learning curve.

Unfortunately, that curve can also affect who is allowed to learn a program and how fast they learn it (not the general public on a budget).

In the current era, SketchUp and its parent company have stuck to the mandate of helping you “visualize your ideas.” The company encourages its users to use sustainable design practices in their creations, and through its app you can also share your designs within the 3D SketchUp community as a whole.

While all these features are very neat, they might not be something you need to explore if you’re still learning the basics. Fortunately, SketchUp has several different plans for users to choose from, including a free version that can be accessed through the web.

Is Google SketchUp Free?

Google SketchUp Download

Yes and no. While there is a free version of Trimble’s (Google) SketchUp, it is very pared down when you compare it to the professional paid version of the app.

SketchUp Free

  • With the basic version of SketchUp, the intent of the program is to help you “discover 3D modeling.”
  • This app is web-only, which means you can only use SketchUp online.
  • You have 10GB of cloud storage for your projects, along with community support via the forums.
  • The downside to the free version is that it does not allow you to use custom styles, custom materials, performance-based designs, or the style builder tool. You also cannot use the models you are creating in the free version of SketchUp for commercial intent.

SketchUp Shop

  • In comparison, SketchUp Shop, the paid version of SketchUp for personal use, allows for basic access to custom styles.
  • It also includes more features like unlimited cloud storage and email support.
  • While SketchUp Shop does have more features, it still doesn’t give you full access to the program. Still, if you end up really loving this program, it’s worth a shot for $119/year.

SketchUp Pro

  • If you want to have full access to the program, or if you’re a professional designer, then you need to use SketchUp Pro.
  • SketchUp Pro gives you access to all features. It can also be used on desktop or through the web.
  • However, this version of the program is the most expensive by far, sitting at $299/year without accounting for seasonal sales, as can be seen in the picture above.

Our Verdict: While SketchUp is not free to use if you’re a designer, if you’re just learning the basics, this free version will work just fine. Additionally, if you use it in conjunction with our beginner’s guide to 3D printing, you’ll have every angle of your 3D modeling hobby covered.

Let’s walk through the basic interface for SketchUp’s free app.

How to Use SketchUp: A Basic Introduction

Trimble SketchUp Free

The great thing about SketchUp is that when you sign up for the free app, you’re offered a guided tour. There are also accessible help forums that will guide you through your very first 3D project, with topics ranging from using SketchUp in comics, to sharing SketchUp projects with a friend.

When you open SketchUp, you should see a “working space” with a three-dimensional axis, a horizon line, and a 2D person for scale. On the left-hand side of your screen, you will see your Toolbar (shown here in red):

SketchUp Toolbar

This Toolbar contains the items that you will need to draw. Here, you’ll be able to locate your:

  • Eraser
  • Paint tools
  • Line tools
  • Push/Pull tools
  • Move tools
  • Tape Measure tools
  • Orbit controls

At the bottom of your screen, you’ll see your Status bar. The Status bar will help you learn how to use SketchUp by clicking on the Help button to access the app’s tutorials.

SketchUp Status Bar

Finally, on the right side of the screen, you will see your Panel section. Here, you can adjust your model using different materials, components, and layers.

SketchUp Panel

To Recap:

  • Draw in SketchUp using your left-hand Toolbar.
  • Adjust your drawing with your right-hand Panel.
  • Learn how to draw with your bottom Status bar.

Try SketchUp If You’re Interested in 3D Modeling

Now that you know all about SketchUp and how to use the basic interface, you can look into the free version of the program and try it out yourself. The best thing about SketchUp is that if you decide to upgrade from Free to Shop or Pro, you can do so easily.

If you’re looking for more information on the world of 3D modeling, check out our list of the best free 3D modeling software.

Read the full article: How to Use SketchUp for 3D Design

non critical

via MakeUseOf.com https://ift.tt/1AUAxdL

June 4, 2020 at 02:24PM

How to setup Specific Subdomain routing in Laravel

How to setup Specific Subdomain routing in Laravel

https://ift.tt/2zwdmjw

Hi all, this is Adi, again with another Laravel post. In one of my recent projects, I had to set up specific subdomain routing within the same Laravel application. This was something new to me because on most projects, I just work with one domain and everything is accessed / after it. I am going to share with you how I solved it, I hope it gives you some ideas when you are faced to do this too. Let’s get started.

What was my need

First, let’s explore my requirements for this project. My client wanted to access the admin portal from the admin.myapp.com domain, the marketing website from myapp.com, and the API from api.myapp.com. As you can see it defers from Laravel’s defaults. By default, Laravel exposes API routes in myapp.com/api url and everything else in myapp.com/ domain.

My Solution

Laravel routing provides a convenient way to setup subdomain routing but it works best only when you have a wildcard routing, this *.myapp.com works but to make specific subdomain to work, I had to do some config changes as well. Below is my routes\web.php file.

Routes File

My routes file
As you can see, you can use the domain method to mention the subdomain you want to capture, but it becomes complicated when you have multiple environments with different domains you need to use, that’s why I have added the SITE_URL variable to my .env file. So when I am developing locally I can set it to localhost, when in production I set the actual domain, and when in staging or testing I can set the relevant domains.

.env Config

My .env config file
It’s just another .env variable you set. Pretty simple.

Webserver Config

Now you have the routing configured but you need to make a few changes in the webserver setup also to be able to use multiple domain names for the same host. Let’s see how.

Local development

I use a windows PC for development, I had to change my hosts files in the system32 folder. I added these entries.
My Hosts file config
Now, if you go to any of these domains, it should be routed to your Laravel application, when it’s being served.

Conclusion

I hope this post helped you. It’s not daily that you come across a config like this, that’s why I decided to share it. If you would like me to cover a specific issue you have with Laravel, do let me know I’ll try to write a post about it.

Related Resources

Thank You
That’s all for now, this has been Adi.
If you are looking for a Freelance Web Developer you can contact me

programming

via Laravel News Links https://ift.tt/2dvygAJ

June 3, 2020 at 08:45PM

Consuming REST APIs In React With Fetch And Axios

Consuming REST APIs In React With Fetch And Axios

https://ift.tt/2BnRrLK

Consuming REST APIs In React With Fetch And Axios

Shedrack Akintayo



Consuming REST APIs in a React Application can be done in various ways, but in this tutorial, we will be discussing how we can consume REST APIs using two of the most popular methods known as Axios (a promise-based HTTP client) and Fetch API (a browser in-built web API). I will discuss and implement each of these methods in detail and shed light on some of the cool features each of them have to offer.

APIs are what we can use to supercharge our React applications with data. There are certain operations that can’t be done on the client-side, so these operations are implemented on the server-side. We can then use the APIs to consume the data on the client-side.

APIs consist of a set of data, that is often in JSON format with specified endpoints. When we access data from an API, we want to access specific endpoints within that API framework. We can also say that an API is a contractual agreement between two services over the shape of request and response. The code is just a byproduct. It also contains the terms of this data exchange.

In React, there are various ways we can consume REST APIs in our applications, these ways include using the JavaScript inbuilt fetch() method and Axios which is a promise-based HTTP client for the browser and Node.js.

Note: A good knowledge of ReactJS, React Hooks, JavaScript and CSS will come in handy as you work your way throughout this tutorial.

Let’s get started with learning more about the REST API.

What Is A REST API

A REST API is an API that follows what is structured in accordance with the REST Structure for APIs. REST stands for “Representational State Transfer”. It consists of various rules that developers follow when creating APIs.

The Benefits Of REST APIs

  1. Very easy to learn and understand;
  2. It provides developers with the ability to organize complicated applications into simple resources;
  3. It easy for external clients to build on your REST API without any complications;
  4. It is very easy to scale;
  5. A REST API is not language or platform-specific, but can be consumed with any language or run on any platform.

An Example Of A REST API Response

The way a REST API is structured depends on the product it’s been made for — but the rules of REST must be followed.

The sample response below is from the Github Open API. We’ll be using this API to build a React app later on in this tutorial.

{
"login": "hacktivist123",
"id": 26572907,
"node_id": "MDQ6VXNlcjI2NTcyOTA3",
"avatar_url": "https://avatars3.githubusercontent.com/u/26572907?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/hacktivist123",
"html_url": "https://github.com/hacktivist123",
"followers_url": "https://api.github.com/users/hacktivist123/followers",
"following_url": "https://api.github.com/users/hacktivist123/following{/other_user}",
"gists_url": "https://api.github.com/users/hacktivist123/gists{/gist_id}",
"starred_url": "https://api.github.com/users/hacktivist123/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/hacktivist123/subscriptions",
"organizations_url": "https://api.github.com/users/hacktivist123/orgs",
"repos_url": "https://api.github.com/users/hacktivist123/repos",
"events_url": "https://api.github.com/users/hacktivist123/events{/privacy}",
"received_events_url": "https://api.github.com/users/hacktivist123/received_events",
"type": "User",
"site_admin": false,
"name": "Shedrack akintayo",
"company": null,
"blog": "https://sheddy.xyz",
"location": "Lagos, Nigeria ",
"email": null,
"hireable": true,
"bio": "☕ Software Engineer | | Developer Advocate🥑|| ❤ Everything JavaScript",
"public_repos": 68,
"public_gists": 1,
"followers": 130,
"following": 246,
"created_at": "2017-03-21T12:55:48Z",
"updated_at": "2020-05-11T13:02:57Z"
} 

The response above is from the Github REST API when I make a GET request to the following endpoint https://api.github.com/users/hacktivist123. It returns all the stored data about a user called hacktivist123. With this response, we can decide to render it whichever way we like in our React app.

Consuming APIs Using The Fetch API

The fetch() API is an inbuilt JavaScript method for getting resources from a server or an API endpoint. It’s similar to XMLHttpRequest, but the fetch API provides a more powerful and flexible feature set.

It defines concepts such as CORS and the HTTP Origin header semantics, supplanting their separate definitions elsewhere.

The fetch() API method always takes in a compulsory argument, which is the path or URL to the resource you want to fetch. It returns a promise that points to the response from the request, whether the request is successful or not. You can also optionally pass in an init options object as the second argument.

Once a response has been fetched, there are several inbuilt methods available to define what the body content is and how it should be handled.

The Difference Between The Fetch API And jQuery Ajax

The Fetch API is different from jQuery Ajax in three main ways, which are:

  1. The promise returned from a fetch() request will not reject when there’s an HTTP error, no matter the nature of the response status. Instead, it will resolve the request normally, if the response status code is a 400 or 500 type code, it’ll set the ok status. A request will only be rejected either because of network failure or if something is preventing the request from completing
  2. fetch() will not allow the use of cross-site cookies i.e you cannot carry out a cross-site session using fetch()
  3. fetch() will also not send cookies by default unless you set the credentials in the init option.

Parameters For The Fetch API

  • resource
    This is the path to the resource you want to fetch, this can either be a direct link to the resource path or a request object
  • init
    This is an object containing any custom setting or credentials you’ll like to provide for your fetch() request. The following are a few of the possible options that can be contained in the init object:

    • method
      This is for specifying the HTTP request method e.g GET, POST, etc.
    • headers
      This is for specifying any headers you would like to add to your request, usually contained in an object or an object literal.
    • body
      This is for specifying a body that you want to add to your request: this can be a Blob, BufferSource, FormData, URLSearchParams, USVString, or ReadableStream object
    • mode
      This is for specifying the mode you want to use for the request, e.g., cors, no-cors, or same-origin.
    • credentials
      This for specifying the request credentials you want to use for the request, this option must be provided if you consider sending cookies automatically for the current domain.

Basic Syntax for Using the Fetch() API

A basic fetch request is really simple to write, take a look at the following code:

fetch('https://api.github.com/users/hacktivist123/repos')
  .then(response => response.json())
  .then(data => console.log(data));

In the code above, we are fetching data from a URL that returns data as JSON and then printing it to the console. The simplest form of using fetch() often takes just one argument which is the path to the resource you want to fetch and then return a promise containing the response from the fetch request. This response is an object.

The response is just a regular HTTP response and not the actual JSON. In other to get the JSON body content from the response, we’d have to change the response to actual JSON using the json() method on the response.

Using Fetch API In React Apps

Using the Fetch API in React Apps is the normal way we’d use the Fetch API in javascript, there is no change in syntax, the only issue is deciding where to make the fetch request in our React Apps. Most fetch requests or any HTTP request of any sort is usually done in a React Component.

This request can either be made inside a Lifecycle Method if your component is a Class Component or inside a useEffect() React Hook if your component is a Functional Component.

For example, In the code below, we will make a fetch request inside a class component, which means we’ll have to do it inside a lifecycle method. In this particular case, our fetch request will be made inside a componentDidMount lifecycle method because we want to make the request just after our React Component has mounted.

import React from 'react';

class myComponent extends React.Component {
  componentDidMount() {
    const apiUrl = 'https://api.github.com/users/hacktivist123/repos';
    fetch(apiUrl)
      .then((response) => response.json())
      .then((data) => console.log('This is your data', data));
  }
  render() {
    return <h1>my Component has Mounted, Check the browser 'console' </h1>;
  }
}
o
export default myComponent;

In the code above, we are creating a very simple class component that makes a fetch request that logs the final data from the fetch request we have made to the API URL into the browser console after the React component has finished mounting.

The fetch() method takes in the path to the resource we want to fetch, which is assigned to a variable called apiUrl. After the fetch request has been completed it returns a promise that contains a response object. Then, we are extracting the JSON body content from the response using the json() method, finally we log the final data from the promise into the console.

Let’s Consume A REST API With Fetch Method

In this section, we will be building a simple react application that consumes an external API, we will be using the Fetch method to consume the API.

The simple application will display all the repositories and their description that belongs to a particular user. For this tutorial, I’ll be using my GitHub username, you can also use yours if you wish.

The first thing we need to do is to generate our React app by using create-react-app:

npx create-react-app myRepos

The command above will bootstrap a new React app for us. As soon as our new app has been created, all that’s left to do is to run the following command and begin coding:

npm start

If our React is created properly we should see this in our browser window when we navigate to localhost:3000 after running the above command.


Initial App Screen
(Large preview)

In your src folder, create a new folder called component. This folder will hold all of our React components. In the new folder, create two files titled List.js and withListLoading.js. These two files will hold the components that will be needed in our app.

The List.js file will handle the display of our Repositories in the form of a list, and the withListLoading.js file will hold a higher-order component that will be displayed when the Fetch request we will be making is still ongoing.

In the List.js file we created inside the components folder, let’s paste in the following code:

import React from 'react';
const List = (props) => {
  const { repos } = props;
  if (!repos) return null;
  if (repos.length === 0) return <p>No repos, sorry</p>;
  return (
    <ul>
      <h2 className='list-head'>Available Public Repositories</h2>
      {repos.map((repo) => {
        return (
          <li key={repo.id} className='list'>
            <span className='repo-text'>{repo.name} </span>
            <span className='repo-description'>{repo.description}</span>
          </li>
        );
      })}
    </ul>
  );
};
export default List;

The code above is a basic React list component that would display the data, in this case, the repositories name and their descriptions in a list.

Now, Let me explain the code bit by bit.

const { repos } = props;

We are initializing a prop for the component called repos.

if (!repos) return null;
  if (repos.length === 0) return 

No repos, sorry

;

Here, all we are doing is making a conditional statement that will render a message when the length of the repos we get from the request we make is equal to zero.

return (
    <ul>
      <h2 className='list-head'>Available Public Repositories</h2>
      {repos.map((repo) => {
        return (
          <li key={repo.id} className='list'>
            <span className='repo-text'>{repo.name} </span>
            <span className='repo-description'>{repo.description}</span>
          </li>
        );
      })}
    </ul>
  );

Here, we are mapping through each of the repositories that will be provided by the API request we make and extracting each of the repositories names and their descriptions then we are displaying each of them in a list.

export default List;

Here we are exporting our List component so that we can use it somewhere else.

In the withListLoading.js file we created inside the components folder, let’s paste in the following code:

import React from 'react';

function WithListLoading(Component) {
  return function WihLoadingComponent({ isLoading, ...props }) {
    if (!isLoading) return <Component {...props} />;
    return (
      <p style=>
        Hold on, fetching data may take some time :)
      </p>
    );
  };
}
export default WithListLoading;

The code above is a higher-order React component that takes in another component and then returns some logic. In our case, our higher component will wait to check if the current isLoading state of the component it takes is true or false. If the current isLoading state is true, it will display a message Hold on, fetching data may take some time 🙂. Immediately the isLoading state changes to false it’ll render the component it took in. In our case, it’ll render the List component.

In your *App.js file inside the src folder, let’s paste in the following code:

import React, { useEffect, useState } from 'react';
import './App.css';
import List from './components/List';
import withListLoading from './components/withListLoading';
function App() {
  const ListLoading = withListLoading(List);
  const [AppState, SetAppState] = useState({
    loading: false,
    repos: null,
  });

  useEffect(() => {
    SetAppState({ loading: true });
    const user = `https://api.github.com/users/hacktivist123/repos`;
    fetch(user)
      .then((res) => res.json())
      .then((repos) => {
        SetAppState({ loading: false, repos: repos });
      });
  }, [SetAppState]);
  return (
    <div className='App'>
      <div className='container'>
        <h1>My Repositories</h1>
      </div>
      <div className='repo-container'>
        <ListLoading isLoading={AppState.loading} repos={AppState.repos} />
      </div>
      <footer>
        <div className='footer'>
          Built{' '}
          <span role='img' aria-label='emoji'>
            💚
          </span>{' '}
          with by Shedrack Akintayo
        </div>
      </footer>
    </div>
  );
}
export default App;

Our App.js is a functional component that makes use of React Hooks for handling state and also side effects. If you’re not familiar with React Hooks, read my Getting Started with React Hooks Guide.

Let me explain the code above bit by bit.

import React, { useEffect, useState } from 'react';
import './App.css';
import List from './components/List';
import withListLoading from './components/withListLoading';

Here, we are importing all the external files we need and also the components we created in our components folder. We are also importing the React Hooks we need from React.

const ListLoading = withListLoading(List);
  const [AppState, SetAppState] = useState({
    loading: false,
    repos: null,
  });

Here, we are creating a new component called ListLoading and assigning our withListLoading higher-order component wrapped around our list component. We are then creating our state values loading and repos using the useState() React Hook.

useEffect(() => {
    SetAppState({ loading: true });
    const user = `https://api.github.com/users/hacktivist123/repos`;
    fetch(user)
      .then((res) => res.json())
      .then((repos) => {
        SetAppState({ loading: false, repos: repos });
      });
  }, [SetAppState]);

Here, we are initializing a useEffect() React Hook. In the useEffect() hook, we are setting our initial loading state to true, while this is true, our higher-order component will display a message.
We are then creating a constant variable called user and assigning the API URL we’ll be getting the repositories data from.

We are then making a basic fetch() request like we discussed above and then after the request is done we are setting the app loading state to false and populating the repos state with the data we got from the request.

return (
    <div className='App'>
      <div className='container'>
        <h1>My Repositories</h1>
      </div>
      <div className='repo-container'>
        <ListLoading isLoading={AppState.loading} repos={AppState.repos} />
      </div>
    </div>
  );
}
export default App;

Here we are basically just rendering the Component we assigned our higher-order component to and also filling the isLoading prop and repos prop with their state value.

Now, we should see this in our browser, when the fetch request is still being made, courtesy of our withListLoading higher-order component:


App Loading State
(Large preview)

Now, when the fetch request has completed successfully, we should see the repositories displayed in a list format as below:


Finished App
(Large preview)

Now, let’s style our project a little bit, in your App.css file, copy and paste this code.

@import url('https://fonts.googleapis.com/css2?family=Amiri&display=swap');
:root {
  --basic-color: #23cc71;
}
.App {
  box-sizing: border-box;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  font-family: 'Amiri', serif;
  overflow: hidden;
}
.container {
  display: flex;
  flex-direction: row;
}
.container h1 {
  font-size: 60px;
  text-align: center;
  color: var(--basic-color);
}
.repo-container {
  width: 50%;
  height: 700px;
  margin: 50px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.3);
  overflow: scroll;
}
@media screen and (max-width: 600px) {
  .repo-container {
    width: 100%;
    margin: 0;
    box-shadow: none;
  }
}
.repo-text {
  font-weight: 600;
}
.repo-description {
  font-weight: 600;
  font-style: bold;
  color: var(--basic-color);
}
.list-head {
  text-align: center;
  font-weight: 800;
  text-transform: uppercase;
}
.footer {
  font-size: 15px;
  font-weight: 600;
}
.list {
  list-style: circle;
}

So in the code above, we are styling our app to look more pleasing to the eyes, we have assigned various class names to each element in our App.js file and thus we are using these class names to style our app.

Once we’ve applied our styling, our app should look like this:


Styled App
(Large preview)

Now our app looks much better. 😊

So that’s how we can use the Fetch API to consume a REST API. In the next section, we’ll be discussing Axios and how we can use it to consume the same API in the same App.

Consuming APIs With Axios

Axios is an easy to use promise-based HTTP client for the browser and node.js. Since Axios is promise-based, we can take advantage of async and await for more readable and asynchronous code. With Axios, we get the ability to intercept and cancel request, it also has a built-in feature that provides client-side protection against cross-site request forgery.

Features Of Axios

  • Request and response interception
  • Streamlined error handling
  • Protection against XSRF
  • Support for upload progress
  • Response timeout
  • The ability to cancel requests
  • Support for older browsers
  • Automatic JSON data transformation

Making Requests With Axios

Making HTTP Requests with Axios is quite easy. The code below is basically how to make an HTTP request.

// Make a GET request
axios({
  method: 'get',
  url: 'https://api.github.com/users/hacktivist123',
});

// Make a Post Request
axios({
  method: 'post',
  url: '/login',
  data: {
    firstName: 'shedrack',
    lastName: 'akintayo'
  }
});

The code above shows the basic ways we can make a GET and POST HTTP request with Axios.

Axios also provides a set of shorthand method for performing different HTTP requests. The Methods are as follows:

  • axios.request(config)
  • axios.get(url[, config])
  • axios.delete(url[, config])
  • axios.head(url[, config])
  • axios.options(url[, config])
  • axios.post(url[, data[, config]])
  • axios.put(url[, data[, config]])
  • axios.patch(url[, data[, config]])

For example, if we want to make a similar request like the example code above but with the shorthand methods we can do it like so:

// Make a GET request with a shorthand method
axios.get(
  url: 'https://api.github.com/users/hacktivist123',
);

// Make a Post Request with a shorthand method
axios.post('/signup', {
    firstName: 'shedrack',
    lastName: 'akintayo'
});

In the code above, we are making the same request as what we did above but this time with the shorthand method. Axios provides flexibility and makes your HTTP requests even more readable.

Making Multiple Requests With Axios

Axios provides developers the ability to make and handle simultaneous HTTP requests using the axios.all() method. This method takes in an array of arguments and it returns a single promise object that resolves only when all arguments passed in the array have resolved.

For example, we can make multiple requests to the GitHub api using the axios.all() method like so:

axios.all([
  axios.get('https://api.github.com/users/hacktivist123'),
  axios.get('https://api.github.com/users/adenekan41')
])
.then(response => {
  console.log('Date created: ', response[0].data.created_at);
  console.log('Date created: ', response[1].data.created_at);
});

The code above makes simultaneous requests to an array of arguments in parallel and returns the response data, in our case, it will log to the console the created_at object from each of the API responses.

Let’s Consume A REST API With Axios Client

In this section, all we’ll be doing is replacing fetch() method with Axios in our existing React Application. All we need to do is to install Axios and then use it in our App.js file for making the HTTP request to the GitHub API.

Now let’s install Axios in our React app by running either of the following:

With NPM:

npm install axios

With Yarn:

yarn add axios

After installation is complete, we have to import axios into our App.js. In our App.js we’ll add the following line to the top of our App.js file:

import axios from 'axios'

After adding the line of code our App.js all we have to do inside our useEffect() is to write the following code:

useEffect(() => {
    SetAppState({ loading: true });
    const user = 'https://api.github.com/users/hacktivist123/repos';
    axios.get(user).then((repos) => {
      const allRepos = repos.data;
      SetAppState({ loading: false, repos: allRepos });
    });
  }, [SetAppState]);

If you’ve noticed, we have replaced the fetch API there with the Axios shorthand method axios.get to make a get request to the API.

axios.get(user).then((repos) => {
      const allRepos = repos.data;
      SetAppState({ loading: false, repos: allRepos });
    });

In this block of code, we are making a GET request then we are returning a promise that contains the repos data and assigning the data to a constant variable called allRepos. We are then setting the current loading state to false and also passing the data from the request to the repos state variable.

If we did everything correctly, we should see our app still render the same way without any change.


App with Axios
(Large preview)

So this is how we can use Axios client to consume a REST API.

Fetch vs Axios

In this section, I will be listing our certain features and then I’ll talk about how well Fetch and Axios support these features.

  1. Basic Syntax
    Both Fetch and Axios have very simple syntaxes for making requests. But Axios has an upper hand because Axios automatically converts a response to JSON, so when using Axios we skip the step of converting the response to JSON, unlike Fetch() where we’d still have to convert the response to JSON. Lastly, Axios shorthand methods allow us to make specific HTTP Requests easier.

  2. Browser Compatibility
    One of the many reasons why developers would prefer Axios over Fetch is because Axios is supported across major browsers and versions unlike Fetch that is only supported in Chrome 42+, Firefox 39+, Edge 14+, and Safari 10.1+.

  3. Handling Response Timeout
    Setting a timeout for responses is very easy to do in Axios by making use of the timeout option inside the request object. But in Fetch, it is not that easy to do this. Fetch provides a similar feature by using the AbortController() interface but it takes more time to implement and can get confusing.

  4. Intercepting HTTP Requests
    Axios allows developers to intercept HTTP requests. HTTP interceptors are needed when we need to change HTTP requests from our application to the server. Interceptors give us the ability to do that without having to write extra code.

  5. Making Multiple Requests Simultaneously
    Axios allows us to make multiple HTTP requests with the use of the axios.all() method ( I talked about this above). fetch() provides the same feature with the use of the promise.all() method, we can make multiple fetch() requests inside it.

Conclusion

Axios and fetch() are all great ways of consuming APIs but I advise you to use fetch() when building relatively small applications and make use of Axios when building large applications for scalability reasons.
I hope you enjoyed working through this tutorial, you could always read more on Consuming REST APIs with either Fetch or Axios from the references below. If you have any questions, you can leave it in the comments section below and I’ll be happy to answer every single one.

Related Resources

Smashing Editorial
(ks, ra, il)

geeky

via Smashing Magazine https://ift.tt/2ibDzra

June 3, 2020 at 08:00AM