0Pricing
React Native Academy · บทเรียน

การส่งคำขอ GET ด้วย Axios

ติดตั้ง Axios ส่งคำขอ GET ไปยังเอพีไอสาธารณะภายใน useEffect จัดเก็บการตอบกลับไว้ในสถานะ และแสดงข้อมูลที่ดึงมาใน FlatList

การส่งคำขอ GET ด้วย Axios เป็นบทเรียน React Native Academy ฟรีบน CoddyKit นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน React Native Academy และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส React Native Academy มีบทเรียนทั้งหมด 4 บทเรียน

บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ

Why Axios Over Fetch?

fetch is built into React Native but requires boilerplate: manually calling .json(), checking response.ok for HTTP errors, and handling timeouts. Axios is an HTTP client library that automatically parses JSON responses, throws on HTTP error status codes, supports request timeouts natively, and provides a clean interceptor API for global headers and error handling.

Installing Axios

Add Axios to your project with npm or yarn. It has no native dependencies, so no additional linking steps are required for either Expo or bare React Native projects.

npm install axios
# or
yarn add axios

Your First GET Request

Call axios.get(url) to make a GET request. It returns a Promise that resolves to a response object. The response body is already parsed as JSON and available on response.data. You do not need to call .json() as you would with fetch.

import axios from 'axios';

axios.get('https://jsonplaceholder.typicode.com/posts')
  .then((response) => {
    console.log(response.data); // parsed JSON array
  })
  .catch((error) => {
    console.error(error.message);
  });

Axios GET Inside useEffect

Combine Axios with useEffect to fetch data when the component mounts. Store the response data in state with useState. Handle errors and show a loading indicator while the request is in flight. The empty dependency array ensures the fetch only happens once on mount.

function PostsScreen() {
  const [posts, setPosts] = useState([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    axios.get('https://jsonplaceholder.typicode.com/posts')
      .then((res) => setPosts(res.data))
      .catch((err) => console.error(err))
      .finally(() => setLoading(false));
  }, []);

  if (loading) return <ActivityIndicator />;
  return <FlatList data={posts} keyExtractor={(p) => String(p.id)} renderItem={({ item }) => <Text>{item.title}</Text>} />;
}

Async/Await with Axios

Axios works naturally with async/await. Define an async function inside the useEffect callback, call it immediately, and wrap the Axios call in a try/catch block. Do not make the useEffect callback itself async — instead, define the async function inside and call it.

useEffect(() => {
  const fetchPosts = async () => {
    try {
      const response = await axios.get('/posts');
      setPosts(response.data);
    } catch (error) {
      setError(error.message);
    } finally {
      setLoading(false);
    }
  };

  fetchPosts();
}, []);

Creating an Axios Instance

Create a shared Axios instance with a baseURL and default headers. Every request made with this instance automatically uses these defaults. This avoids repeating the full URL in every component and makes it easy to update the base URL or add an authorization header in one place.

// api/client.js
import axios from 'axios';

const client = axios.create({
  baseURL: 'https://api.myapp.com/v1',
  timeout: 10000,
  headers: { 'Content-Type': 'application/json' },
});

export default client;

// Usage: just the path
client.get('/posts') // → GET https://api.myapp.com/v1/posts

Sending Query Parameters

Pass query string parameters via the params option in the Axios config object. Axios serializes the params object and appends them to the URL automatically. This is cleaner than manually building query strings and URL-encoding values.

// Request: GET /posts?userId=1&_limit=5
const response = await axios.get('/posts', {
  params: {
    userId: 1,
    _limit: 5,
  },
});

console.log(response.data); // array of up to 5 posts by userId 1

Adding Authorization Headers

Attach a bearer token to requests either globally via an Axios instance default or per-request via the config object. Use Axios request interceptors to automatically attach a token stored in AsyncStorage or an auth context without modifying every individual request.

// Per-request
axios.get('/user/profile', {
  headers: { Authorization: 'Bearer ' + token },
});

// Global via interceptor
client.interceptors.request.use((config) => {
  config.headers.Authorization = 'Bearer ' + getToken();
  return config;
});

Reading the Response Structure

Every Axios response object has a consistent shape: data for the parsed response body, status for the HTTP status code, statusText, and headers. Unlike fetch, Axios automatically throws an error for 4xx and 5xx status codes, so the .catch or try/catch handles both network errors and HTTP errors.

const response = await axios.get('/posts/1');
console.log(response.data);        // { id: 1, title: '...' }
console.log(response.status);      // 200
console.log(response.headers);     // { 'content-type': 'application/json' }

Cancelling Axios Requests

To cancel an Axios request in the useEffect cleanup function, pass an AbortController signal (Axios supports this natively from v0.22+). When the component unmounts, call controller.abort() to cancel any in-flight request and prevent state updates on unmounted components.

useEffect(() => {
  const controller = new AbortController();

  axios.get('/posts', { signal: controller.signal })
    .then((res) => setPosts(res.data))
    .catch((err) => {
      if (!axios.isCancel(err)) setError(err.message);
    });

  return () => controller.abort();
}, []);

Rendering Fetched Data in FlatList

Once data is stored in state, pass it directly to FlatList's data prop. Because the state update triggers a re-render, the FlatList automatically shows the new data. This one-way data flow — fetch → state → render — is the core React pattern for data display.

return (
  <FlatList
    data={posts}
    keyExtractor={(item) => String(item.id)}
    renderItem={({ item }) => (
      <View style={styles.row}>
        <Text style={styles.title}>{item.title}</Text>
        <Text style={styles.body} numberOfLines={2}>{item.body}</Text>
      </View>
    )}
  />
);

Quick Check

Test your understanding of making GET requests with Axios from this lesson.

Lesson Recap

In this lesson you learned: axios.get returns a Promise that resolves to response.data as parsed JSON, create an Axios instance with a baseURL and default headers for reuse across components, and pass an AbortController signal to cancel in-flight requests in useEffect cleanup. Next up we handle loading and error states for a polished user experience.

คำถามที่พบบ่อย

บทเรียน “การส่งคำขอ GET ด้วย Axios” ฟรีหรือไม่

ใช่ — ข้อความเต็มของ “การส่งคำขอ GET ด้วย Axios” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส React Native Academy ให้อัปเกรดเป็น CoddyKit PRO คอร์ส React Native Academy มีบทเรียนทั้งหมด 4 บทเรียน

คุณจะเรียนรู้อะไรในบทเรียน “การส่งคำขอ GET ด้วย Axios”

ติดตั้ง Axios ส่งคำขอ GET ไปยังเอพีไอสาธารณะภายใน useEffect จัดเก็บการตอบกลับไว้ในสถานะ และแสดงข้อมูลที่ดึงมาใน FlatList คุณปฏิบัติ React Native Academy ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน

คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน React Native Academy หรือไม่

ไม่จำเป็นต้องมีประสบการณ์มาก่อน React Native Academy บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน

บทเรียน “การส่งคำขอ GET ด้วย Axios” ใช้เวลานานแค่ไหน

บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย

ฉันเขียนและรันโค้ดในบทเรียน React Native Academy นี้ได้ไหม

ได้ บทเรียน React Native Academy ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ

บทเรียนทั้งหมดในหลักสูตรนี้

  1. ฮุก useEffect และอาร์เรย์การพึ่งพา
  2. การส่งคำขอ GET ด้วย Axios
  3. การจัดการสถานะกำลังโหลดและข้อผิดพลาด
  4. POST, PUT และ DELETE ด้วย Axios
← กลับไปที่ React Native Academy