react fetch data from api example

How to Fetch Data from API with React Hooks | Example

If you haven't one already, you can create react application using create-react-app by running this command.

create-react-app <YOUR_APP_NAME>

After successfully created app, create a file fetchData in /src/fetchData.js.

About useEffect() :

If you’re familiar with React class lifecycle methods, you can think of useEffect Hook as componentDidMount, componentDidUpdate, and componentWillUnmount combined. You should check out the docs.

Note –
Inside the component where you want to fetch a data, you must need to add a useEffect hook i.e.

import React, { useEffect } from "react"

export default () => {

    useEffect(() => {
        // Fetch data right here!
    }, [])

    return (
        <>
            <h1>You are welcome!</h1>
        </>
    )
}

As an Example, to load countries –
import React, { useEffectuseState } from 'react';
import axios from 'axios';

export default () => {
    const [countriessetCountries] = useState([]);
    const [loadsetLoad] = useState(false);
    const [errorsetError] = useState('');

    useEffect(() => {
        axios.get('https://restcountries.eu/rest/v2/all')
            .then(result => {
                setCountries(result.data);
                setLoad(true);
            })
            .catch(err => {
                setError(err.message);
                setLoad(true)
            })
    }, []);

    if (load) {
        return (<>
            {error ?
                <div>{error.message}</div> :
                countries.map((vali=> <div key={i}> {i} - {val.name}</div>)
            }
        </>)
    } else {
        return (
            <>
                Loading...
            </>
        );
    }
};

The result looks like,

ANIL SINGH

Anil Singh is an author, tech blogger, and software programmer. Book writing, tech blogging is something do extra and Anil love doing it. For more detail, kindly refer to this link..
My Blogs - https://code-sample.com and https://code-sample.xyz
My Book1 - BEST SELLING ANGULAR BOOK (INCLUDING ALL VERSIONS 2, 4, 5, 6, 7)
My Book2 - ANGULAR 2 INTERVIEW QUESTIONS BOOK - Both Books are Available on WorldWide.

www.code-sample.com/. Powered by Blogger.
^