Unhandled Rejection (TypeError): Cannot read property 'method' of undefined
Есть модуль:
async function request(url, { method = 'GET', body = null, headers = {} }) {
console.log(method)
let loading = false;
let error = null;
let data = null;
try {
const response = await fetch(url, { method, body, headers });
const data_ = await response.json();
data = data_;
loading = true;
} catch (err) {
error = err.message;
loading = true;
}
return { loading, data, error }
}
export default request;
const topNews = request('http://localhost:5500/api/news/top/2');
Почему-то при вызове request() выдает ошибку:
Unhandled Rejection (TypeError): Cannot read property 'method' of undefined
Ответы (1 шт):
Автор решения: vsemozhebuty
→ Ссылка
Даже если вы задаёте параметры по умолчанию в деструктурировании, функция не сможет деструктурировать отсутствующий объект. Есть два решения.
- Передать пустой объект в аргументе:
const topNews = request('http://localhost:5500/api/news/top/2', {});
- Задать пустой объект по умолчанию в параметре:
async function request(url, { method = 'GET', body = null, headers = {} } = {}) {