ReactJS call api backend
reactTo call a backend API from a ReactJS app, you can use the fetch() function or a library like Axios.
Here is an example of using fetch() to make a GET request to an API:
async function getData() {
const response = await fetch('/api/endpoint');
const data = await response.json();
console.log(data);
}
Here is an example of using Axios to make a GET request to an API:
import axios from 'axios';
async function getData() {
const response = await axios.get('/api/endpoint');
console.log(response.data);
}
Both of these examples assume that the API is hosted on the same domain as the ReactJS app. If the API is hosted on a different domain, you may need to specify the full URL of the API in the fetch() or axios.get() call.
You can use similar approaches to make other types of requests (such as POST, PUT, or DELETE) to the API.
It’s a good idea to familiarize yourself with the fetch() function and libraries like Axios so that you can choose the most appropriate approach
Here is an example of how you can use the fetch function to call an API and retrieve data from the backend:
import React, {useState, useEffect} from 'react';
function App() {
const [data, setData] = useState(null);
useEffect(() => {
async function fetchData() {
const response = await fetch('https://api.example.com/endpoint');
const json = await response.json();
setData(json);
}
fetchData();
}, []);
return (
<div>
{data ? (
<pre>{JSON.stringify(data, null, 2)}</pre>
) : (
'Loading...'
)}
</div>
);
}
export default App;
In this example, the App component uses the useEffect hook to call the API when the component is mounted. The fetch function is used to send an HTTP request to the API and retrieve the response. The response is then parsed as JSON and stored in the data state variable using the setData function. The data variable is then rendered in the component’s render method.
Other Article on Tag react
- - A cross-origin error was thrown. React doesn't have access to the actual error object in
- - react add bootstrap
- - react add semantic-ui
- - react call backend api
- - react navbar code example
- - react register and login page example
- - ReactJS Animation
- - ReactJS Building and Deployment
- - ReactJS call api backend
- - ReactJS Component