Anthony Bryant

1583746320

A Simple React Hook to help you with Data Fetching

UFO - Use fetch orderly .A simple React hook to help you with data fetching

Fetch API and Axios help you fetching data but when you need to link the status of a request to your React state you are on your own.

Handling the UI state related to a request can be repetitive and error-prone, especially if you have to

  • handle related requests within the same component
  • ignore requests results after your component is unmounted
  • abort requests in certain conditions
  • handle race conditions

Taking advantage of React hooks react-ufo helps you deal with this complexity.

Installation

npm install --save react-ufo

import {useFetcher} from "react-ufo"

How to use

Basic usage

useFetcher handles the state of a request for you and much more.

The minimal usage of useFetcher looks like the following:

const [callback, [loading, error, data]] = useFetcher(fetcher)

A fetcher function is a normal function that fetches some data and returns a promise.

Here an example of fetcher function:

const getTodo = async (id) => {
  const response = await fetch("https://jsonplaceholder.typicode.com/todos/" + id);
  return response.json();
};

When you want your request to start, all you need to do is to invoke callback, after doing so, loading, error, and data will be updated in accordance with the status of your request.

Any argument you pass to callback will be passed to your fetcher.

Note:
Do not create a new fetcher function on every render, useFetcher will create a new callback anytime a new fetcher instance is received. In case your fetcher depends on props simply pass them to callback and your fetcher will receive them.

Here a basic example showing how to use useFetcher in an event callback such as onClick Edit 1basicFetchInEventCallbackExample

Fetching on mount/update

By default, before a request is started, useFetcher will return loading=false, error=null, data=null.

Sometimes you might want your initial request state to be different.

One example is if you plan to request your data on the component mount/update, in this case, you might want your initial request state to have loading=true.

useFetcher can receive a second argument indicating the initial state before your request starts.

Here how you override the default loading state to be true

const [callback, [loading, error, data]] = useFetcher(fetcher, {loading:true})

Now if you want your request to start on mount all you need to do is

useEffect(()=>{
  callback()
},[callback])

You don’t have to worry about passing callback as a dependency of useEffect, callback will only change if your fetcher changes.

Fetching on mount/update with props

Sometimes a fetcher might need some data in order to retrieve data, for example, the getTodo presented earlier needs an id argument.

Assuming id is a prop of your component all you need to do is

useEffect(()=>{
  callback(id)
},[id,callback])

this ensures that your fetcher will be invoked on mount and anytime id updates, which is usually what you want.

Here a basic example showing how to use useFetcher during mount/update Edit 2basicFetchOnMountAndUpdateExample

Cascading fetches

Sometimes 2 requests depend on each other.

Let’s say that you fetched a todo object containing a userId field and you want to use userId to fetch a user object.

Here how you can handle this use case with useFetcher


...

const [fetchTodo, [loadingTodo, todoError, todo]] = useFetcher(todoFetcher, {loading:true})
const [fetchUser, [loadingUser, userError, user]] = useFetcher(userFetcher, {loading:true})

useEffect(()=>{
  fetchTodo(todoId).then((todo)=>{
    fetchUser(todo.userId)
  })
},[todoId, fetchTodo, fetchUser])

...

Here the full example showing this use case Edit 4cascadingFetchesExample

Ignoring a pending request

If your component is unmounted while one of its requests is still pending useFetcher will take care of ignoring its result avoiding an attempt to perform a setState on an unmounted component.

Sometimes you might want to ignore the result of a request for other reasons too.

callback.ignore() can be invoked if you need to ignore the result of a pending request.

If a pending request is marked as ignored loading, error and data will not be updated once the request is completed.

Aborting a pending request

callback.abort() can be invoked anytime you want to abort a pending request.

Unfortunately in order for callback.abort() to work properly there is some little more wiring that you’ll need to do.

useFetcher will take care of passing an abort signal to your fetcher as its last argument.

In order for callback.abort() to work you’ll need to pass the abort signal to your Fetch API.

Here an example showing how to enable fetch abortion on the getTodo fetcher presented earlier

const getTodo = async (id, signal) => {
  const response = await fetch("https://jsonplaceholder.typicode.com/todos/" + id, {signal});
  return response.json();
};

If your fetcher is not passing the abort signal to fetch API invoking callback.abort() will not abort the request but the request will still be marked as ignored.

If a request is marked as ignored loading, error and data will not be updated once the request is completed.

Here an example showing how to abort a request Edit 3basicAbortFetchExample

Aborting a pending request is quite easy when using Fetch API but it can also be achieved if you are using other libraries such as axios

If you are wondering how to abort a request started by Axios instead of Fetch API you can find an example here Edit abortRequestIfUsingAxiosExample

Keeping state between fetches

By default useFetcher erases the data of a request anytime a new one is started.

Most of the times this is what you want but there are cases where you want to keep the data visible to the user until new data are retrieved.

If you need to keep data between fetches you can simply use useState from React.

Here an example showing how to keep data while multiple request are pending:

const [data, setData] = useState()
const [callback, [loading, error, _data]] = useFetcher(fetcher)

...

const myEventCallback = ()=>{
  callback(1).then((data)=>{
    setData(data)
    callback(2).then((data)=>{
        setData(data)
    })
  })
} 

In the previous example _data is set to null anytime a new request is started while data is only valued when a request is completed.

Debouncing requests

Here an example showing one simple way to debounce requests Edit 5debounceFetchExample

Mutating state

Sometimes you might want to change your request state manually.

One common scenario when this can happen is if your user decides to ignore and remove a request error message displayed on the screen.

useFetcher provides you setLoading, setError, setData and setRequestState for you to handle these use cases.

Here the full signature of useFetcher:

const [callback, [loading, error, data], setRequestState] = useFetcher(fetcher)
const [setLoading, setError, setData] = setRequestState

setLoading, setError, setData and setRequestState should be self explanatory, they work exactly like the setState in const [state, setState] = useState()

Putting all together

Here an example showing how useFetcher can be used to implement a simple CRUD application Edit 6crudExample

useFetcher API

Here the full useFetcher API

const initialRequestState = {loading:false, error:null, data:null} //these are the default values if initialRequestState is not provided
const [callback, requestState, setRequestState] = useFetcher(fetcher, initialRequestState)
const [loading, error, data] = requestState
const [setLoading, setError, setData] = setRequestState

What exactly is useFetcher returning?

useFetcher returns a result object shaped as follow:

{
  callback,
  requestState: {
    loading,
    error,
    data
  },
  setRequestState: {
    setLoading,
    setError,
    setData
  }
}

result, requestState and setRequestState are also iterable, therefore, if you find it convenient for renaming, you can destructure them into an array as follow

const [callback, [loading, error, data], [setLoading, setError, setData]] = result

When destructuring into an array you obviously need to rely on the order we specified for each key, therefore, in case you don’t want to extract all the fields from result, you might need to write something like the following:

const [callback, [loading, , data], [, setError]] = result

Because result is an object, accessing its fields by key (e.g const data = result.requestState.data) is going to work as expected too.

Because result is an object, doing object destructuring is going to work as expected too.

Note that even though setRequestState contains setLoading, setError, setData it is a function and can be used to update loading, error and data in a single render.

Note:
Even though result, requestState and setRequestState are iterable they are not arrays, therefore something like result[0] or result.requestState[0] is not going to work.

Examples

  1. Basic fetch in event callback Edit 1basicFetchInEventCallbackExample
  2. Basic fetch on mount/update Edit 2basicFetchOnMountAndUpdateExample
  3. Aborting a pending request Edit 3basicAbortFetchExample
  4. Handling requests depending on each others Edit 4cascadingFetchesExample
  5. Debouncing requests Edit 5debounceFetchExample
  6. Simple CRUD application Edit 6crudExample
  7. Aborting a pending request started with axios Edit abortRequestIfUsingAxiosExample

Package versioning

Breaking changes might be made between 0.x.x versions.
Starting from version 1.0.0 every breaking change will result in a major version update.
The changelog will give you details about every change between versions.

Dependencies

This package has zero dependencies but in order to support fetches abortion you will need AbortController (or a polyfill such as abortcontroller-polyfill) in your environment

Download Details:

Author: marcellomontemagno

GitHub: https://github.com/marcellomontemagno/react-ufo

#reactjs #javascript

What is GEEK

Buddha Community

A Simple React Hook to help you with Data Fetching
Autumn  Blick

Autumn Blick

1598839687

How native is React Native? | React Native vs Native App Development

If you are undertaking a mobile app development for your start-up or enterprise, you are likely wondering whether to use React Native. As a popular development framework, React Native helps you to develop near-native mobile apps. However, you are probably also wondering how close you can get to a native app by using React Native. How native is React Native?

In the article, we discuss the similarities between native mobile development and development using React Native. We also touch upon where they differ and how to bridge the gaps. Read on.

A brief introduction to React Native

Let’s briefly set the context first. We will briefly touch upon what React Native is and how it differs from earlier hybrid frameworks.

React Native is a popular JavaScript framework that Facebook has created. You can use this open-source framework to code natively rendering Android and iOS mobile apps. You can use it to develop web apps too.

Facebook has developed React Native based on React, its JavaScript library. The first release of React Native came in March 2015. At the time of writing this article, the latest stable release of React Native is 0.62.0, and it was released in March 2020.

Although relatively new, React Native has acquired a high degree of popularity. The “Stack Overflow Developer Survey 2019” report identifies it as the 8th most loved framework. Facebook, Walmart, and Bloomberg are some of the top companies that use React Native.

The popularity of React Native comes from its advantages. Some of its advantages are as follows:

  • Performance: It delivers optimal performance.
  • Cross-platform development: You can develop both Android and iOS apps with it. The reuse of code expedites development and reduces costs.
  • UI design: React Native enables you to design simple and responsive UI for your mobile app.
  • 3rd party plugins: This framework supports 3rd party plugins.
  • Developer community: A vibrant community of developers support React Native.

Why React Native is fundamentally different from earlier hybrid frameworks

Are you wondering whether React Native is just another of those hybrid frameworks like Ionic or Cordova? It’s not! React Native is fundamentally different from these earlier hybrid frameworks.

React Native is very close to native. Consider the following aspects as described on the React Native website:

  • Access to many native platforms features: The primitives of React Native render to native platform UI. This means that your React Native app will use many native platform APIs as native apps would do.
  • Near-native user experience: React Native provides several native components, and these are platform agnostic.
  • The ease of accessing native APIs: React Native uses a declarative UI paradigm. This enables React Native to interact easily with native platform APIs since React Native wraps existing native code.

Due to these factors, React Native offers many more advantages compared to those earlier hybrid frameworks. We now review them.

#android app #frontend #ios app #mobile app development #benefits of react native #is react native good for mobile app development #native vs #pros and cons of react native #react mobile development #react native development #react native experience #react native framework #react native ios vs android #react native pros and cons #react native vs android #react native vs native #react native vs native performance #react vs native #why react native #why use react native

Siphiwe  Nair

Siphiwe Nair

1620466520

Your Data Architecture: Simple Best Practices for Your Data Strategy

If you accumulate data on which you base your decision-making as an organization, you should probably think about your data architecture and possible best practices.

If you accumulate data on which you base your decision-making as an organization, you most probably need to think about your data architecture and consider possible best practices. Gaining a competitive edge, remaining customer-centric to the greatest extent possible, and streamlining processes to get on-the-button outcomes can all be traced back to an organization’s capacity to build a future-ready data architecture.

In what follows, we offer a short overview of the overarching capabilities of data architecture. These include user-centricity, elasticity, robustness, and the capacity to ensure the seamless flow of data at all times. Added to these are automation enablement, plus security and data governance considerations. These points from our checklist for what we perceive to be an anticipatory analytics ecosystem.

#big data #data science #big data analytics #data analysis #data architecture #data transformation #data platform #data strategy #cloud data platform #data acquisition

What are hooks in React JS? - INFO AT ONE

In this article, you will learn what are hooks in React JS? and when to use react hooks? React JS is developed by Facebook in the year 2013. There are many students and the new developers who have confusion between react and hooks in react. Well, it is not different, react is a programming language and hooks is a function which is used in react programming language.
Read More:- https://infoatone.com/what-are-hooks-in-react-js/

#react #hooks in react #react hooks example #react js projects for beginners #what are hooks in react js? #when to use react hooks

Gerhard  Brink

Gerhard Brink

1620629020

Getting Started With Data Lakes

Frameworks for Efficient Enterprise Analytics

The opportunities big data offers also come with very real challenges that many organizations are facing today. Often, it’s finding the most cost-effective, scalable way to store and process boundless volumes of data in multiple formats that come from a growing number of sources. Then organizations need the analytical capabilities and flexibility to turn this data into insights that can meet their specific business objectives.

This Refcard dives into how a data lake helps tackle these challenges at both ends — from its enhanced architecture that’s designed for efficient data ingestion, storage, and management to its advanced analytics functionality and performance flexibility. You’ll also explore key benefits and common use cases.

Introduction

As technology continues to evolve with new data sources, such as IoT sensors and social media churning out large volumes of data, there has never been a better time to discuss the possibilities and challenges of managing such data for varying analytical insights. In this Refcard, we dig deep into how data lakes solve the problem of storing and processing enormous amounts of data. While doing so, we also explore the benefits of data lakes, their use cases, and how they differ from data warehouses (DWHs).


This is a preview of the Getting Started With Data Lakes Refcard. To read the entire Refcard, please download the PDF from the link above.

#big data #data analytics #data analysis #business analytics #data warehouse #data storage #data lake #data lake architecture #data lake governance #data lake management

Database Vs Data Warehouse Vs Data Lake: A Simple Explanation

Databases store data in a structured form. The structure makes it possible to find and edit data. With their structured structure, databases are used for data management, data storage, data evaluation, and targeted processing of data.
In this sense, data is all information that is to be saved and later reused in various contexts. These can be date and time values, texts, addresses, numbers, but also pictures. The data should be able to be evaluated and processed later.

The amount of data the database could store is limited, so enterprise companies tend to use data warehouses, which are versions for huge streams of data.

#data-warehouse #data-lake #cloud-data-warehouse #what-is-aws-data-lake #data-science #data-analytics #database #big-data #web-monetization