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!!!

ReactJs new Experience

very interesting video1 corse
very interesting video2 corse
very interesting video3 corse
very interesting video4 corse Use Ref
very interesting video5 cource useDispach

Flex container tutorial very fine

source code here

from here

best from here

Create Project  :  npx create-react-app form

Install bootstrap : npm install react-bootstrap bootstrap

vs

Install martial-ui : npm install @material-ui/core @material-ui/icons

useful commands with Simple React Snippet installed in VCode

Comment Code Block Ctrl+K+C/Ctrl+K+U

Snippets

Snippet Renders
imr Import React
imrc Import React / Component
imrs Import React / useState
imrse Import React / useState useEffect
impt Import PropTypes
impc Import React / PureComponent
cc Class Component
ccc Class Component With Constructor
cpc Class Pure Component
sfc Stateless Function Component
cdm componentDidMount
uef useEffect Hook
cwm componentWillMount
cwrp componentWillReceiveProps
gds getDerivedStateFromProps
scu shouldComponentUpdate
cwu componentWillUpdate
cdu componentDidUpdate
cwu componentWillUpdate
cdc componentDidCatch
gsbu getSnapshotBeforeUpdate
ss setState
ssf Functional setState
usf Declare a new state variable using State Hook
ren render
rprop Render Prop
hoc Higher Order Component

react native snippets install plugin in visual code

rfc

 

syntax example code :

tag : [‘tag1’, ‘tag2’, ‘tag3’]

{tags.map(tag => <li key={tag.id}>{tag}</li>)}

tags.map((item, index) => (

<FormControlLabel  value={item.id} control={<Radio />}  label={item.title}>

))

 

handleIncrement() {

if “this” is called in a part of a method of object : obj.method()  this is the reference of the obj

if “this” is called in the function : function() return a reference to the window

object so can be undefined id the strict mode is enabled

}

contructor() {

super();// referring to the extend class ex Component

console.log(‘Contructor’, this);

this.handleIncrement = this.handleIncrement.bind(this);

}

OR

handleIncrement = () => {

console.log(‘Contructor’, this);

}

setState(prevState => {
return { …prevState, {count: prevState.count – 1} }
})

ADD a router

create-react-app material-ui-react-router

OR

npm install react-router-dom

here

install datepicker MUI  npm i @material-ui/pickers npm i @date-io/date-fns@1.x date-fns

npm install @material-ui/lab
npm install axios

 

I can use the ThremeProvider in the index.js to import the default theme to customize

align grid content

dashboard and google fonts

const [index, setIndex] = useState(0);
const [shiftArr, setShiftArr] = useState([]);

update react project :

sudo npm install -g npm-check-updates