Ways of Getting Data from API in React

from here

React library is a wonderful tool for building rich and highly scalable user interfaces. One of its powerful features is the possibility to fetch data for the web application from the outside and interact with it.

Why to Fetch Data?

When you are just starting developing web applications with React, you probably won’t need any external data at the beginning. You will build a simple applications like ToDo app or Counter and add your data to the state object of your application. And that is totally fine.

However, at some point you want to request real world data from an own or a third-party API. For example, if you want to build a book store or weather application, it is faster and convenient to use one of those free data sources available in the Internet.

Where to Do Data Fetching

Now that we have decided that we want to fetch data from external source, here comes the question – where exactly in our application we should do that?

This question depends the following criteria:

  • who is interested in data?
  • who will show the loading indicator in case data is pending?
  • where to show an optional error message when the request fails?

Usually this is a common parent component in the components tree who will do this job. It will fetch the data, store it to its local state and distribute it to the children:

1. On the first mounting of the component
We use this way when we want the data to be accessible when we first start the application. It means, we need to perform data fetching when our parent component is being mounted.

In class-based components the perfect place for data fetching is componentDidMount() lifecycle method.

In functional components it is useEffect() hook with an empty dependancy array because we need the data to be fetched once.

2. On event being triggered
We can fetch data on triggering an event (for example button click) by creating a function, which will make data fetching and then binding that function to the event.

Ways of Fetching Data

There are many ways to extract data from API in React:

  1. using Fetch API
  2. using Axios library
  3. using async-await syntax
  4. using custom hooks
  5. using React Query library
  6. using GrapthQL API

We will explore these ways now in details.

1. Fetching Data with Fetch API

Fetch API is built into most modern browsers on the window object (window.fetch) and enables us to make HTTP requests very easily using JavaScript promises.

In our CRA we can use fetch() method to get the data. This method accepts just an URL to the data.

To do so, we will create a method called fetchData(). It will call fetch() method with provided URL, then convert the result to JSON object and print it to the console:

const fetchData = () => {
return fetch("https://randomuser.me/api/")
      .then((response) => response.json())
      .then((data) => console.log(data));}

We can use this method now anywhere in the application. Here is an example how to use it in useEffect()hook:

import {useEffect} from "react";

useEffect(() => {
  fetchData();
  }, []);

2. Fetching Data with Axios library

It does the same job as Fetch, but the main difference is that it already returns the result as JSON object, so we don’t need to convert it.

First we need to install it using npm:

npm install axios

Than we need to import it to our project and we can use it in the same function fetchData() instead of fetch() method:

import axios from "axios"

const fetchData = () => {
return axios.get("https://randomuser.me/api/")
      .then((response) => console.log(response.data));}

What’s convenient about using Axios is that it has a much shorter syntax that allows us to cut down on our code and it includes a lot of tools and features which Fetch does not have in its API.

3.Fetching Data with Async-Await syntax

In ES7, it became possible to resolve promises using the async-await syntax. If you are not familiar with such function, check here.

The benefit of this is that it enables us to remove our .then() callbacks and simply get back our asynchronously resolved data.

Lets re-write our fetchData() function using this syntax:

async function fetchData() {
    try {
      const result = await axios.get("https://randomuser.me/api/")
      console.log(result.data));
    } catch (error) {
      console.error(error);
    }
  }

4.Fetching Data with Custom Hook

We can use the library React-Fetch-Hook to extract the data from API. It includes already several properties we can use: dataerror for errors handling and isLoading for loading issues.

First it should be installed:

npm install react-fetch-hook

Then it should be imported and used on top of common parent component:

import useFetch from "react-fetch-hook"

const {data} = useFetch("https://randomuser.me/api/");
console.log(data);

There are other ways for data fetching as React Query library and GraphQL API, but this blog post is not covering them in depth, but you are free to explore those 🙂
Happy Fetching!!!

How to Build Your SPF Record in 5 Simple Steps

from here

spf syntax documentation here

To protect your customers, your brand, and your business from phishing and spoofing attacks, you must authenticate your email. SPF (Sender Policy Framework) is an authentication protocol that allows senders to specify which IP addresses are authorized to send email on behalf of a particular domain.

An SPF-protected domain is less attractive to fraudsters and is therefore less likely to be blacklisted by spam filters. SPF also ensures that legitimate email from the domain is delivered.

Ready to create your SPF record? Follow these five simple steps.

Step 1: Gather IP addresses that are used to send email
The first step to implement SPF is to identify which mail servers you use to send email from your domain. Many organizations send mail from a variety of places. Make a list of all your mail servers, and be sure to consider whether any of the following is used to send email on behalf of your brand:

  • Web server
  • In-office mail server (e.g., Microsoft Exchange)
  • Your ISP’s mail server
  • The mail server of your end users’ mailbox provider
  • Any other third-party mail server used to send email on behalf of your brand

Step 2: Make a list of your sending domains
Chances are, your company owns many domains. Some of these domains are used to send email. Others are not.

It is important to create SPF records for all the domains you control, even the ones you’re not mailing from. Why? Because once you have protected your sending domains with SPF, the first thing a criminal will do is try to spoof your non-sending domains.

Step 3: Create your SPF record
SPF authenticates a sender’s identity by comparing the sending mail server’s IP address to the list of authorized sending IP addresses published by the sender in the DNS record. Here’s how to create your SPF record:

  • Start with v=spf1 (version 1) tag and follow it with the IP addresses that are authorized to send mail. For example, v=spf1 ip4:1.2.3.4 ip4:2.3.4.5
  • If you use a third party to send email on behalf of the domain in question, you must add an “include” statement in your SPF record (e.g., include:thirdparty.com) to designate that third party as a legitimate sender
  • Once you have added all authorized IP addresses and include statements, end your record with an ~all or -all tag
  • An ~all tag indicates a soft SPF fail while an -all tag indicates a hard SPF fail. In the eyes of the major mailbox providers ~all and -all will both result in SPF failure. Return Path recommends an -all as it is the most secure record.
  • SPF records cannot be over 255 characters in length and cannot include more than ten include statements, also known as “lookups.” Here’s an example of what your record might look like:
  • v=spf1 ip4:1.2.3.4 ip4:2.3.4.5 include:thirdparty.com -all
  • For your domains that do not send email, the SPF record will exclude any modifier with the exception of -all. Here’s an example record for a non-sending domain:
  • v=spf1 -all

Congratulations! You’ve created your SPF record. Now, it’s time to publish it.

Step 4: Publish your SPF to DNS
Work with your DNS server administrator to publish your SPF record to DNS, so mailbox providers can reference it.

If you’re using a hosting provider such as 123-reg or GoDaddy, then this process is fairly simple. If your DNS records are administered by your ISP or if you aren’t sure, then contact your IT department for support. Email service providers typically publish SPF records for sending domains on your behalf.

Step 5: Test!|
Test your SPF record with a SPF check tool. You will be able to see what recipients see: a list of the servers authorized to send email on behalf of your sending domain. If one or more of your legitimate sending IP addresses is not listed, then you can update your record to include it.