← Back to React Course | Chapter 10: Data Fetching & Async | Lesson 2 of 10

React में Axios का उपयोग

Axios fetch का एक fancier version जैसा है जो automatically response को plain data में translate कर देता है और जब कुछ गलत हो तो clearer error messages देता है।
Syntax
markup
const api = axios.create({ baseURL: "https://api.example.com" });

axios.get(url)
  .then(response => setData(response.data))
  .catch(error => setError(error));

Axios से एक GET Request बनाना

axios.get(url) एक GET request भेजता है और एक Promise return करता है जो directly parsed response data में resolve होता है (response.data के under), fetch() को चाहिए वाले extra .json() step को skip करते हुए।

यह slightly shorter, ज़्यादा consistent API axios के main appeals में से एक है।

Note:
  • response.data actual payload रखता है
  • response.status और response.headers भी ज़रूरत पड़ने पर available हैं।
Warning: fetch() के विपरीत, axios का Promise HTTP error statuses (4xx/5xx) पर automatically reject होता है — किसी manual response.ok check की ज़रूरत नहीं, लेकिन आपको एक .catch() चाहिए।

उदाहरण: Making a GET Request with Axios

markup
// Run in your local React project (npm install required)
import axios from 'axios';

function App() {
  const [data, setData] = React.useState(null);
  React.useEffect(() => {
    axios.get('/api/data').then(response => setData(response.data));
  }, []);
  return <p>{data ? data.message : "Loading..."}</p>;
}

⚠️ This example uses an npm package with no CDN build available here — run this in your local React project.

Axios से Errors Handle करना

चूंकि axios automatically HTTP error statuses पर reject होता है, एक .catch() block (या async/await के साथ try/catch) network failures और server error responses दोनों को एक ही जगह reliably catch करता है, fetch के manual response.ok check की तुलना में error handling simplify करते हुए।

Note: error.response.status HTTP status code देता है जब server ने error के साथ respond किया हो; pure network failures के लिए error.response undefined है।
Warning: Axios के साथ .catch() (या try/catch) भूल जाना किसी भी failed request पर एक unhandled promise rejection का कारण बनता है, fetch के विपरीत जिसे failure notice करने के लिए भी एक extra explicit check चाहिए।

उदाहरण: Handling Errors with Axios

markup
// Run in your local React project (npm install required)
import axios from 'axios';

async function loadData(setError) {
  try {
    const response = await axios.get('/api/data');
    return response.data;
  } catch (error) {
    setError(error.message);
  }
}

⚠️ This example uses an npm package with no CDN build available here — run this in your local React project.

एक Reusable Axios Instance बनाना

axios.create() baseURL और default headers जैसी settings के साथ एक pre-configured instance बनाता है, इसलिए आपको हर single request पर पूरा API URL और auth header दोहराना नहीं पड़ता।

यह instance एक बार बनाया जाता है और पूरे app में जहां ज़रूरत हो वहां import किया जाता है।

Note: Instance में एक बार एक baseURL set करें, फिर हर जगह api.get('https://api.example.com/users') के बजाय api.get('/users') call करें।
Warning: Instance को module scope पर एक बार बनाएं (इसकी own file में), किसी component के अंदर नहीं — इसे हर render पर recreate करना किसी भी benefit को lose करता है।

उदाहरण: Creating a Reusable Axios Instance

markup
// Run in your local React project (npm install required)
import axios from 'axios';

const api = axios.create({
  baseURL: 'https://api.example.com',
  headers: { Authorization: 'Bearer token123' },
});

// Later, anywhere in the app:
// api.get('/users').then(response => console.log(response.data));

⚠️ This example uses an npm package with no CDN build available here — run this in your local React project.

Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. यह भूल जाना कि axios responses already parsed हैं — response.data access करना, fetch जैसे .json() call करने के बजाय।
  2. Axios errors catch न करना, जो (fetch के विपरीत) default रूप से HTTP error statuses पर reject होता है।
  3. Component के बाहर एक बार configure करने के बजाय हर render पर एक नया axios instance बनाना।
चैप्टर सारांश
  • Axios एक popular third-party HTTP client है, जो built-in fetch() से एक friendlier API देता है।
  • fetch के विपरीत, axios automatically JSON responses parse करता है और HTTP error statuses पर अपना promise reject करता है।
  • axios.get/post/put/delete corresponding HTTP methods को directly map करते हैं।
  • axios.create() आपको एक base URL और default headers के साथ एक reusable instance configure करने देता है।
ब्राउज़र सपोर्ट

npm install axios चाहिए — इस sandbox में CDN से उपलब्ध नहीं है; किसी भी React version के साथ काम करता है।

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.