How to handle API calls in a React app using async await

0 votes
Can i know How to handle API calls in a React app using async/await?
Mar 12 in Node-js by Ashutosh
• 23,030 points
34 views

1 answer to this question.

0 votes

You can handle API calls in a React app using async/await inside the useEffect hook.

Example: Fetching Data with Async/Await

import { useState, useEffect } from "react";

function App() {

    const [data, setData] = useState(null);

    const [loading, setLoading] = useState(true);

    useEffect(() => {

        const fetchData = async () => {

            try {

                const response = await fetch("https://jsonplaceholder.typicode.com/posts/1");

                const result = await response.json();

                setData(result);

            } catch (error) {

                console.error("Error fetching data:", error);

            } finally {

                setLoading(false);

            }

        };

        fetchData();

    }, []);

    return (

        <div>

            {loading ? <p>Loading...</p> : <p>{data?.title}</p>}

        </div>

    );

}

export default App;

answered Mar 12 by Sahil

Related Questions In Node-js

0 votes
0 answers

How to manage async API calls in a React app using redux-thunk?

Can you tell me How to manage ...READ MORE

Mar 19 in Node-js by Ashutosh
• 23,030 points
25 views
0 votes
1 answer
0 votes
1 answer

How to Handle Jest Unit Testing for 'ɵcmp' in a React-in-Angular Hybrid App?

Encountering the 'ɵcmp' property error during Jest ...READ MORE

answered Dec 23, 2024 in Node-js by Navya
102 views
0 votes
1 answer

How to use async functions effectively in React components?

To use async functions effectively in React ...READ MORE

answered Mar 12 in Node-js by Sahil
52 views
0 votes
1 answer
0 votes
1 answer

How does Babel differ from JSX?

Feature Babel JSX Definition A JavaScript compiler that transforms ES6+ code ...READ MORE

answered Mar 12 in Java-Script by Sahil
87 views
0 votes
1 answer

How can I install the Babel plugin for JSX syntax?

Use the following commands: npm install @babel/preset-react --save-dev Steps ...READ MORE

answered Mar 12 in Node-js by Sahil
37 views
0 votes
1 answer

How do you handle scroll restoration in a React-Router app?

By default, React Router does not restore ...READ MORE

answered Feb 24 in Node-js by Kavya
118 views
0 votes
1 answer

How do you handle a large amount of data in React?

Handling Large Amounts of Data in React To ...READ MORE

answered Feb 24 in Node-js by Kavya
99 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP