Skip to main content

Session 6: Networking & Promise

Promise là gì?

Many web / mobile apps need to load resources from a remote URL. You may want to make a POST request to a REST API, or you may need to fetch a chunk of static content from another server.

Using Fetch

React provides the Fetch API for your networking needs. Fetch will seem familiar if you have used XMLHttpRequest or other networking APIs before. You may refer to MDN's guide on Using Fetch for additional information.

Making requests

const onSubmit = () => {
const data = {
username: 'tungnt@softech.vn',
password: '123456789',
};

const url = 'https://server.aptech.io/auth/login';
fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
})
.then((response) => response.json())
.then((json) => {
// Xử lý kết quả JSON ở đây
console.log(json);
})
.catch((error) => {
// Nếu có lỗi
console.error(error);
});
};

You can also use the async / await syntax:

const onSubmitAsync = async () => {
try {
const data = {
username: 'tungnt@softech.vn',
password: '123456789',
};

const url = 'https://server.aptech.io/auth/login';
const response = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
});

// Xử lý kết quả JSON ở đây
const json = await response.json();
console.log(json);
} catch (error) {
// Nếu có lỗi
console.error(error);
}
};
tip

Don't forget to catch any errors that may be thrown by fetch, otherwise they will be dropped silently.

Using Axios

Promise based HTTP client for the browser and node.js

https://github.com/axios/axios

Install

npm install axiox --save

or

yarn add axios

Making requests

const onSubmit = () => {
const data = {
username: 'tungnt@softech.vn',
password: '123456789',
};

const url = 'https://server.aptech.io/auth/login';

// Promise
axios
.post(url, data)
.then((result) => {
console.log(result.data);
console.log('Login thành công');
})
.catch((err) => {
console.error(err);
console.log('Login thất bại');
});
};

You can also use the async / await syntax:

const onSubmitAsync = async () => {
const data = {
username: 'tungnt@softech.vn',
password: '123456789',
};

const url = 'https://server.aptech.io/auth/login';

try {
// Promise
const response = await axios.post(url, data);
console.log(response.data);
} catch (err) {
console.error(err);
console.log('Login thất bại');
}
};

Các ví dụ

Lấy danh sách danh mục

GET https://server.aptech.io/online-shop/categories
// using axios

const [categories, setCategories] = useState([]);

React.useEffect(() => {
const url = 'https://server.aptech.io/online-shop/categories';
const get = async () => {
try {
const response = await axios.get(url);
console.log(response.data);
} catch (err) {
console.error(err);
}
};

get();
}, []);

Using React-Query

https://tanstack.com/query/latest