Itโs a good practice to create a specific file that handles API calls. This can help keep your codebase clean and makes it easier to manage all API-related operations in one place. Create a file named api.js in your src directory:
// src/api.js
import axios from 'axios';
const API_BASE_URL = 'https://api.yourdomain.com';
const instance = axios.create({
baseURL: API_BASE_URL,
timeout: 1000,
});
// You can add common headers or auth tokens here
instance.defaults.headers.common['Authorization'] = AUTH_TOKEN;
export const fetchData = async () => {
try {
const response = await instance.get('/endpoint');
return response.data;
} catch (error) {
console.error('Error fetching data: ', error);
// Handle errors here or throw them to be handled where the function is called
throw error;
}
};
Making an API Call from a React Component
Now you can use the fetchData function from the api.js in any React component. Hereโs an example:
// src/App.js
import React, { useEffect, useState } from 'react';
import { fetchData } from './api';
function App() {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
fetchData()
.then(data => {
setData(data);
setLoading(false);
})
.catch(err => {
setError(err);
setLoading(false);
});
}, []);
if (loading) return <p>Loading...</p>;
if (error) return <p>Error loading data!</p>;
return (
<div>
<h1>Data Loaded</h1>
<pre>{JSON.stringify(data, null, 2)}</pre>
</div>
);
}
export default App;
Handling Errors
As shown in the component above, error handling is crucial when making API calls. You can handle errors within the API call function, or directly within the component, depending on how you prefer to manage error states in your application.
Answer from Viram Choksi on Stack OverflowReact.js API calls using Axios - javascript
reactjs - How do I use the get request of axios by sending a query from the user and getting the values from the database for that particular query? - Stack Overflow
axios get request in reactJS - Stack Overflow
How to make an axios get request on button click event in React?
Videos
Itโs a good practice to create a specific file that handles API calls. This can help keep your codebase clean and makes it easier to manage all API-related operations in one place. Create a file named api.js in your src directory:
// src/api.js
import axios from 'axios';
const API_BASE_URL = 'https://api.yourdomain.com';
const instance = axios.create({
baseURL: API_BASE_URL,
timeout: 1000,
});
// You can add common headers or auth tokens here
instance.defaults.headers.common['Authorization'] = AUTH_TOKEN;
export const fetchData = async () => {
try {
const response = await instance.get('/endpoint');
return response.data;
} catch (error) {
console.error('Error fetching data: ', error);
// Handle errors here or throw them to be handled where the function is called
throw error;
}
};
Making an API Call from a React Component
Now you can use the fetchData function from the api.js in any React component. Hereโs an example:
// src/App.js
import React, { useEffect, useState } from 'react';
import { fetchData } from './api';
function App() {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
fetchData()
.then(data => {
setData(data);
setLoading(false);
})
.catch(err => {
setError(err);
setLoading(false);
});
}, []);
if (loading) return <p>Loading...</p>;
if (error) return <p>Error loading data!</p>;
return (
<div>
<h1>Data Loaded</h1>
<pre>{JSON.stringify(data, null, 2)}</pre>
</div>
);
}
export default App;
Handling Errors
As shown in the component above, error handling is crucial when making API calls. You can handle errors within the API call function, or directly within the component, depending on how you prefer to manage error states in your application.
Assuming that you have basic knowledge of React and how the states work.
import React, { useState } from 'react';
import axios from 'axios';
const Page = () => {
const [name, setName] = useState('');
const [password, setPassword] = useState('');
const handleSubmit = async (event) => {
event.preventDefault();
try {
const response = await axios.post('/api', {
name,
password,
});
console.log('Login successful:', response.data);
} catch (error) {
console.error('Login error:', error);
}
};
return (
<form onSubmit={handleSubmit}>
<div>
<label htmlFor="name">Name:</label>
<input
type="text"
id="name"
value={name}
onChange={(event) => setName(event.target.value)}
/>
</div>
<div>
<label htmlFor="password">Password:</label>
<input
type="password"
id="password"
value={password}
onChange={(event) => setPassword(event.target.value)}
/>
</div>
<button type="submit" onClick = {handleSubmit}>Login</button>
</form>
);
};
export default Page;
This is the basic API call using Axios by taking the user input and sending it as payload.
As Chris mentioned you have to create a function with name like update and paste axios up there:
import axios from "axios";
import React, { useState, useEffect } from 'react';
import ReactDOM from 'react-dom';
import '../node_modules/bootstrap/dist/css/bootstrap.min.css';
export default function App() {
const [randomQuote, setRandomQuote] = useState('');
const update = () => {
axios
.get(baseURL)
.then((res) => {
setRandomQuote(res.data);
});
};
useEffect(update, []);
if (!randomQuote) return null;
return (
<div>
<QuoteCard
quote={randomQuote.content}
author={randomQuote.author}
handleClick={update}
/>
</div>
)
}
do it like this:
const handleButtonClick = () => {
axios.get(baseURL)
.then((res)=> {
setRandomQuote(res.data);
});
}
// then pass it to QuoteCard
<div>
<QuoteCard
quote={randomQuote.content}
author={randomQuote.author}
handleClick={handleButtonClick}
/>
</div>
//then in QuoteCard
<div>
<button className="btn btn-secondary" onClick={props.handleClick}>Generate</button>
</div>
ยป npm install axios