In most modern web applications, the back end is separated from the frontend. Therefore, it must fetch data from a remote endpoint(server), by making AJAX requests.
Prerequisites:
Approach:
-
Import React, useState, and useEffect:
- Import React along with the `useState` and `useEffect` hooks for managing state and handling side effects.
-
Fetch Data with useEffect:
- Use the `useEffect` hook to fetch data from “https://catfact.ninja/fact” when the component mounts.
- Update the state variable `text` with the fetched fact or an error message in case of failure.
-
Render JSX:
- Return JSX to display the fetched data or an error message within a styled div with the class “App.”
Steps to Create the React Application And Installing Module:
Step 1: Create a React application using the following command:
npx create-react-app myapp
Step 2: After creating your project folder, i.e. myapp, move to it using the following command:
cd myapp
Project Structure:
Example: Now that we have the project set up, let us replace the content of App.js.
import React, { useState, useEffect } from "react" ;
import './App.css'
const App = () => { const [text, setText] = useState( "Data has not been fetched yet!" );
useEffect(() => {
.then((response) => response.json())
.then(({ fact }) => setText(fact))
. catch ((error) => {
setText( "An error occurred!" );
});
}, []);
return <div className= "App" ><p>{text}</p></div>;
}; export default App;
|
/* Write CSS Here */ .App { /* min-width: 50vw; */
display : flex;
flex- direction : column;
align-items: center ;
justify- content : center ;
text-align : center ;
} body { background-color : antiquewhite;
} p { font-size : 25px ;
color : rgb ( 0 , 167 , 228 );
font-weight : bold ;
} button { width : 10em ;
height : 2em ;
background-color : rgb ( 27 , 24 , 24 );
font-weight : 600 ;
font-family : 'Lucida Sans' , 'Lucida Sans Regular' ,
'Lucida Grande' , 'Lucida Sans Unicode' , Geneva, Verdana , sans-serif ;
color : white ;
border-radius: 6px ;
border : none ;
} button:hover { background-color : rgb ( 96 , 145 , 125 );
} |
Step to run the application: Use the following command to run the app in development mode, and open http://localhost:3000 to view it in the browser:
npm start
Output: