I am trying to fetch 15 articles with a specific tag using Axios. However, on one page there are only 10 results with different tags, hence I have to map the data from multiple pages, following these examples:
How to fetch data over multiple pages?
This is my code so far... obviously, it doesn't work. I believe that the mistake is the last getAllData(urls) because in the chrome dev tools I get an error :
export class Dashboard extends Component {
state = {
articles: [],
};
componentDidMount() {
axios
.get(
"https://content.guardianapis.com/search?api-key=test"
)
.then((res) => {
const urls = [];
const pages = 5;
//let pages = res.data.response.pages;
for (let i = 1; i < pages; i++) {
urls.push(
"https://content.guardianapis.com/search?api-key=test&page=" +
i
);
}
const getAllData = (urls) => {
return Promise.all(urls.map(fetchData));
};
const fetchData = (url) => {
axios
.get(url)
.then((res) => {
return {
data: res.data,
};
})
.catch((err) => {
console.log(err);
});
};
//this is not working console.log(res) undefined ??
getAllData(urls)
.then((res) => {
console.log(res);
this.setState({
articles: res.data.response.results.slice(0, 15),
});
})
.catch((e) => {
console.log(e);
});
});
}
return code
render() {
const { articles } = this.state;
const articleList = articles.length ? (
articles.map((article) => {
if (article.pillarName === "News")
return (
<div
>
<div >
<a >
{article.webTitle}
</a>
</div>
<div >{article.sectionName}</div>
</div>
);
})
) : (
<div>Loading...</div>
)
return (
<div >
{articleList}
</div>
);
I would really appreciate your help, I have been stuck for a while. Thanks