Categories
JavaScript APIs

Introducing the Intersection Observer API

We often have to watch for the visibility of an element within the window or a parent element.

To make this task easy, the Intersection Observer API is available for us to use to do that.

In this article, we’ll look at how to use the Intersection Observer API to watch for visibility changes for a child element.

Uses for the Intersection Observer API

We can use the Intersection Observer API to watch for visibility changes of one element or 2 elements in relation to each other.

Watching these changes is useful for things like:

  • lazy-loading images when an element becomes visible
  • infinite scrolling
  • checking the visibility of ads
  • run tasks only when an element is visible

Using the Intersection Observer API

To use the Intersection Observer API, we register a callback that runs whenever the visibility of an element changes. This means when it enters or leaves the viewport.

The callback is called whenever the element called the target intersection either the device viewport or a specified element.

The device viewport or another specified element is called the root element or root.

We have to specify the target element’s intersection ratio to indicate how much of the element is visible before the callback will be called.

It’s an array that has numbers ranges from 0 to 1, where 0 is not visible and 1 is completely visible.

For instance, given that we have the following elements generated by the following code:

for (let i = 0; i < 100; i++) {
  const p = document.createElement('p');
  p.innerText = i;
  document.body.append(p);
}

The code above creates p elements with a number as the text content.

We can create an IntersectionObserver object as follows:

const ps = document.querySelectorAll('p');
let options = {
  root: null,
  rootMargin: '0px',
  threshold: [0, 0.25, 0.5, 0.75, 1]
}

let callback = (entries, observer) => {
  entries.forEach(entry => {
    console.log(entry.intersectionRatio > 0)
  });
};

let observer = new IntersectionObserver(callback, options);
ps.forEach(p => {
  observer.observe(p);
});

In the code above, we first create our options object, which has root set to null so that we watch the elements relative to the root element.

We can also specify another element that we want to watch the child elements from.

The rootMargin property is the margin around each element that we want to watch. We can specify this value as we do with the value of the margin CSS property.

The threshold property is an array of numbers for which the visibility of each element is watched and the callback is called. In the example above, we specified that the callback is called when the element being watched is 0% visible, 25% visible, 50% visible, 75% visible, and 100% visible.

Next, we create the IntersectionObserver object with the IntersectionObserver constructor with the callback and options that we created earlier passed in.

Then we can observe each p element that was created earlier by writing:

ps.forEach(p => {
  observer.observe(p);
});

Where ps is:

const ps = document.querySelectorAll('p');

which are the p elements that we created earlier.

Then when we scroll up and down the page, we should see true or false logged from the callback when the intersectionRatio of the element is bigger than 0.

If intersectionRatio is bigger than 0 that means the element is at least partly visible. Otherwise, it’s not visible.

To make observing elements more efficient, we can unobserved them when they’re in view.

For instance, we can do that by adding observer.unobserve(entry.target); into our callback as follows:

let callback = (entries, observer) => {
  entries.forEach(entry => {
    if (entry.intersectionRatio > 0) {
      observer.unobserve(entry.target);
    }
  });
};

We can also manipulate the elements in the callback when the intersectionRatio or any other property changes as follows:

let callback = (entries, observer) => {
  entries.forEach(entry => {
    if (entry.intersectionRatio > 0.75) {
      entry.target.classList.add('highlight');
    } else {
      entry.target.classList.remove('highlight');
    }
  });
};

In the code above, we add the highlight class to the p element when the intersectionRatio is bigger than 0.75. This means the given element is more than 75% visible.

Given that the highlight class has the following CSS:

.highlight {
  color: green;
}

We get that the color of the text is green when the text is more than 75% visible on the page.

Conclusion

The Intersection Observer API makes it easy to see whether an element is visible or not. We can watch for changes in each element that we want to check the visibility of and then do things like add and remove classes or styles accordingly.

We can also unobserve elements that don’t need to be watched if we want to make our code more efficient.

Categories
Useful APIs

Free APIs That We Can Use to Make Entertaining and Useful Apps

In the software development world, practice makes perfect. Therefore, we should find as many ways to practice programming as possible.

With free public APIs, we can practice programming by creating apps that use those APIs.

In this article, we’ll look at some practice project ideas that can use some of those APIs.

Joke App

With the Chuck Norris Database API, we can make our own apps to display jokes about Chuck Norris.

We can display them however we like. We can display them randomly, get jokes by category, and whatever another way we can think of.

No authentication is required, so we can dig in without signing up.

Trivia Game

The Open Trivia API has a list of questions that are provided via their API. Each quest has both correct and incorrect answers.

Therefore, we can use it to make a trivia game app with ease. We can just display the questions and the choices and we can check against the answers that are listed.

No authentication is required, so we can dig in without signing up.

Donald Trump Quotes App

The Tronald Dump API provides us with what Donald Trump has said since he’s become a famous person.

There’re many ways to use them and display the quotes in entertaining ways.

No authentication is required, so we can dig in without signing up.

Comic App

With the xkcd API, we can get all the comics from xkcd without any effort.

We just have to make a request for each comic by ID and then we can display the comic provided as an image URL and the metadata in our own app.

No authentication is required, so we can dig in without signing up.

Bing Maps App

Bing Maps is a great resource for map data. We can use it to display maps, get geographies data, street view, routing information, location data, and much more.

It’s often overlooked since Google is the dominating maps provider, but Bing also provides tons of data for free or a low price.

To use the data, we have to sign up for an API key to gain access to it.

Google Maps App

Google Maps is the maps API that everyone thinks of when they look for a map API.

It also has free and paid tiers with much of the same information as provided by the Bing Maps API.

All we have to do is to sign up for an API key. However, do note that a credit card is required to sign up even for the free tier.

Coronavirus Tracker

The COVID-19 API has the latest data from John’s Hopkins University about the cases of the COVID-19 disease that’s been spreading for the last few months all over the world.

It has recorded data from the past and also the latest infection case data.

If we want to know when we can get out of the house again, then build an app with this and check the trends ourselves.

No authentication is required, so we can just start using it.

US Health Insurance App

The Healthcare.gov API has data about the American insurance marketplace that we can get in no time.

It’s all available as JSON so we can display them the way we like. It has education content like explaining what the insurance marketplace, so we can learn more from them.

Job Search App

Various job websites have provided their data via their API in addition to their regular website.

They include Github Jobs, GraphQL Jobs, Indeed, ZipRecruiter and more for jobs from any category, including the public and private sectors.

There’s plenty of data like description, name, location, and more. Also, we can search for them by keyword or location, which is very handy.

To gain access to them, we just have to sign up for an API key and then we can start playing with these APIs.

To make an app that lets us display and search for public sector jobs data, we can use the Search.gov Jobs API.

It has a full list of endpoints that we can call to gain access to federal jobs data, including searching by location, hiring paths, who qualify for which job, and more.

Conclusion

We can build lots of apps with free public APIs. They include job search apps, maps apps, and health info apps.

If we want some entertainment, we can also build apps that display and make a trivia game out of some trivial APIs.

Categories
JavaScript APIs

Using the React-Redux Hooks API to Manipulate Store State

With Redux, we can use it to store data in a central location in our JavaScript app. It can work alone and it’s also a popular state management solution for React apps when combined with React-Redux.

In this article, we’ll look at how to use the useDispatch and useStore hooks in the React-Redux hooks API, and also look at performance and stale state issues.

useDispatch

We can use the useDispatch hook to get the dispatch function to dispatch actions to the store.

For example, we use useDispatch as follows:

import React from "react";
import ReactDOM from "react-dom";
import { Provider, useSelector, useDispatch } from "react-redux";
import { createStore } from "redux";

function count(state = 0, action) {
  switch (action.type) {
    case "INCREMENT":
      return state + 1;
    case "DECREMENT":
      return state - 1;
    default:
      return state;
  }
}

const store = createStore(count);

function App() {
  const count = useSelector(state => state);
  const dispatch = useDispatch();
  return (
    <div className="App">
      <button onClick={() => dispatch({ type: "INCREMENT" })}>Increment</button>
      <button onClick={() => dispatch({ type: "DECREMENT" })}>Decrement</button>
      <p>{count}</p>
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(
  <Provider store={store}>
    <App />
  </Provider>,
  rootElement
);

In the code above, we called useDispatch in App to get the dispatch function so that we can dispatch actions from the store.

Then we create functions that call dispatch to pass into the onClick prop.

useStore

We can use the useStore hook to get the reference to the Redux store. It’s the same one that we passed into the Provider component.

This shouldn’t be used frequently since we aren’t supposed to access the store directly within a React app since it doesn’t update according to the React update cycle.

Stale Props and “Zombie Children”

Stale props mean that a selector function relies on a component’s props to extract data, a parent component would re-render and pass down new props as a result of an action, but the component’s selector functions execute before the component has a chance to re-render with those new props.

This causes outdated data to be displayed. in the child component or an error being thrown.

“Zombie child” refers to the cases where multiple nested connected components are mounted ina first pass, causing a child component to subscribe to the store before its parent. Then an action is dispatched that deletes data from the store. The parent component would stop rendering the child as a result.

Because the child subscribed to the store first, its subscription runs before the parent stops render. When it reads a value based on props, the data no longer exists. Then an error may be thrown when the extraction logic doesn’t check for the case of the missing data.

Therefore, we should rely on props in our selector function for extracting data.

connect adds the necessary subscription to the context provider and delays evaluating child subscriptions until the connected component has re-rendered. Putting a connected component in the component tree just above the component using useSelector will prevent the issues above.

Performance

useSelector will do a reference equality comparison of the selected value when running the selector function after an action is dispatched.

It’ll only re-render if the previous state is different from the current state. connect and useSelector doesn’t prevent the component from re-rendering because of its parent re-rendering.

To stop parent re-rendering from re-rendering the child, we can use memoization to prevent that.

For example, we can write the following:

import React from "react";
import ReactDOM from "react-dom";
import { Provider, useSelector, useDispatch } from "react-redux";
import { createStore } from "redux";

function count(state = 0, action) {
  switch (action.type) {
    case "INCREMENT":
      return state + 1;
    case "DECREMENT":
      return state - 1;
    default:
      return state;
  }
}

const store = createStore(count);

function App() {
  const count = useSelector(state => state);
  const dispatch = useDispatch();
  return (
    <div className="App">
      <button onClick={() => dispatch({ type: "INCREMENT" })}>Increment</button>
      <button onClick={() => dispatch({ type: "DECREMENT" })}>Decrement</button>
      <p>{count}</p>
    </div>
  );
}

App = React.memo(App);

const rootElement = document.getElementById("root");
ReactDOM.render(
  <Provider store={store}>
    <App />
  </Provider>,
  rootElement
);

In the code above, we added the React.memo call as follows:

App = React.memo(App);

to cache existing results and preventing re-render if the state remains the same.

Conclusion

We can use the useDispatch hook to get the dispatch function to update the store’s state.

There’s also a useStore hook to get a reference of the Redux store in our React components.

However, we shouldn’t access the store directly with useStore since we’re supposed to use useSelector to get the latest state from the store and use useDispatch to dispatch actions.

Also, we have to be aware of stale props from parent components and child components that have been removed because of state changes throwing errors and displaying incorrect data.

We should also memoize the state of components to cache them so that they don’t have to re-render when nothing changed.

Categories
Useful APIs

Useful Practice Apps We Can Build With Free APIs

In the software development world, practice makes perfect. Therefore, we should find as many ways to practice programming as possible.

With free public APIs, we can practice programming by creating apps that use those APIs. After writing the practice apps, we can even pay for some APIs and write even more useful apps.

In this article, we’ll look at some practice project ideas that can use some of those APIs.

Phone Number Validator

We can use the numverify API to verify phone numbers to make sure that they’re valid.

Now we won’t have to worry about calling phone numbers that might not be used by anyone.

It works with phone numbers from 232 countries and can give us the phone company and location that the phone number is located in.

Git App

The big Git hosts all provide their own APIs to let us automate tasks that are needed to be done with them like pulling and pushing code, merging code, etc.

There’s Bitbucket, GitHub, and Gitlab, which all let us do many Git operations with them.

They’re all very secure as authentication is done using OAuth and authorization is the same as using the UI to manipulate the Git repositories.

Website / RSS Aggregator

With the import.io API, we can aggregate data from various websites and RSS feeds and get them all from one source.

It supports CORS so we can access data right from our front end apps. An API key is required to use this API.

The data that’s aggregated with import.io is returned in JSON so that we can use the data right away.

We can use it to crawl websites and RSS feeds and extract data as we wish. Jobs can be run on the fly and also run on a scheduled basis by setting a schedule with the API.

An App to Find Technologies Use On Other Websites

Ever curious about what technologies on websites that we visit? We can use the Let’s Validate API to create an app that reveals the technologies that are used on websites of our choice.

It doesn’t require any authentication so that we can use them right away.

API Testing App

We can use the Postman API to make our own requests to APIs with ease. It lets us write programs to script the testing of APIs by using the Postman API.

The Postman API can be used to send query strings, headers, and get response bodies and headers.

Dictionary App

With various APIs, we can create our own dictionary app with various dictionary APIs.

There’s the Merriam-Webster API, Oxford dictionary API, Wordnik API, and the Words API.

They’re all available for free as long we limit our queries and sign up for an API key to use them.

They provide definitions of words, pronunciations, word types, and more data.

In the case of the Words API, it also provides synonyms for words. The Oxford dictionary API also has a thesaurus, translations for words, sentences API to get us example sentences for a given word, and more.

If we pay, then we get access to more things like more API requests a day

File Conversion App

The Cloudmersive Document and Data Conversion app lets us write the programs to use the API to convert data between various formats.

They include converting between common formats like HTML, Office files, or photo files to PDF.

We can also use it to merge multiple Office documents into one.

Other data formats that the API can convert include CSV to JSON and XML to JSON.

Cloudmersive also makes other APIs like email validation APIs, natural language processing APIs, OCR APIs, barcode scanning APIs and more.

It can take images and then parse them into readable text with the OCR API. The barcode scanner API takes images of the barcode and returns the data from the barcode.

Conclusion

There’re lots of APIs that we can use to do various things like converting files, barcode scanning, OCR, and more.

We can also use APIs to automate Git operations like pushing, fetching, and pulling code from to and from repos.

Finally, we can validate data like phone numbers with various APIs.

Categories
Useful APIs

Free APIs We Can Use to Build Productivity and Recreational Apps

In the software development world, practice makes perfect. Therefore, we should find as many ways to practice programming as possible. With free public APIs, we can practice programming by creating apps that use those APIs.

In this article, we’ll look at some practice project ideas that can use some of those APIs.

HTML to PDF Converter

We can use the pdflayer API to convert HTML documents from files and URLs to PDFs.

All we need is an API key and then we can use it convert HTML to PDFs with little effort.

Document Bookmarker

The Pocket API lets us use their bookmarking service to add, change, and remove bookmarks via their API.

It let us automate the process and view articles that are bookmarked via the API.

With the Article View API, the whole document’s content is returned and we can use it to display the data.

To-Do Lists

We can use some todo list APIs like Todoist and Wunderlist to create our own programs to create todo lists that save that on those service providers via their APIs.

The Todoist API can do a lot like creating projects, templates, items, labels, notes, project notes, file uploads, etc.

Also, we can create set reminders and due dates for todo tasks.

These are things that’ll take a lot of effort on our end to do. With this API, we can do that with half the effort since we eliminated the need to build an API to do all that.

The Wunderlist API has similar capabilities. We can do the same things with it, put add memberships for accessing todo lists.

And we can create webhooks to create todo lists.

Event Information App

There’s APIs for big event websites like Eventbrite, Picatic, Ticketmaster which can be used to retrieve events.

The Eventbrite API gives us access to their API via OAuth. It gives us data on event capacity, description, schedule, teams, and more.

We can also get data on organizations’ data including their members and their roles.

Furthermore, we can get the seat map for various venues with it.

The Ticketmaster API provides similar data as the Eventbrite API so that we can get the same kind of data with it. The difference is that we use an API key for authentication instead of OAuth.

Food and Drink Apps

We can get data from various food and drink APIs like the LCBO API to get alcohol data from the government liquor store in Ontario, Canada.

It has data on images, winery information, retail locations of the liquor store chain, inventory of liquor in different locations and more.

If we want to create a food app, we can create an app using the Recipe Puppy API.

The API only has one endpoint. We can search for recipes store in the database behind the API with the keywords we enter in.

It supports pagination so that it won’t overwhelm their API servers.

Restaurant App

A restaurant app is a useful app for discovering restaurants. Frameworks like the Zomato API lets us get information like restaurant name and location, reviews, menus, etc.

All we need is an API key to access their data.

We can also get restaurant data organized by various things like categories, cities, collections, cuisines, and geolocation coordinates.

It can also be used to find the daily menu, restaurant info, and reviews for a given restaurant.

Beer App

With the PunkAPI, we can create our own app to look up beer information.

No authentication is required for this API, but there’s a rate limit for a given IP address.

It returns data like beer name, the yeast beer is made from, the year range that the beer is brewed, and the hops and malt content.

It can also return a random beer.

Conclusion

We can do a lot with free APIs. There are APIs to convert HTML to PDF, so we can make our own document format converter app.

Also, we can get data about restaurants, food, recipes, drinks, and more if we’re interested in food. Therefore, we can use them to make our own apps to search and display the data our way.

Finally, we can make our own apps to display event and venue data so that we can display the data the way we want to.