I'm new to Nextjs, and I've been tinkering with a newsfeed tool to become familiar with the framework. I want to fetch data from list of RSS feeds. I've been tinkering around with it, and it's not functioning the way I thought it should. How would i go about doing it?
Here is my code:
import { useEffect, useState } from 'react';
export default function Articles() {
const [items, setItems] = useState([]);
const [error, setError] = useState(null);
useEffect(() => {
async function fetchData() {
try {
const res = await fetch('https://api.rss2json.com/v1/api.json?rss_url=http%3A%2F%2Frss.cnn.com%2Frss%2Fcnn_topstories.rss&api_key=kiu9hxfe1661vn0cmz3jpj8dueorj0idmiucugqr');
const data = await res.json();
const items = data.items.slice(0, 20);
setItems(items);
} catch {
setError(true);
}
}
fetchData();
}, []);
if (error) {
return (
<section>
<div>
<h3>Latest Articles</h3>
<ul>
<p>Failed to fetch data, please try again later.</p>
</ul>
<a
href={"https://www.cnn.com/"}
target={"_blank"}
rel={"noopener noreferrer"}
>
Read on CNN
</a>
</div>
</section>
);
}
return (
<section>
<div>
<h3>Latest Articles</h3>
<ul>
{items.map((item, index) => (
<div key={index}>
<a href={item.link} target={"_blank"}>
<h3>{item.title}</h3>
</a>
</div>
))}
</ul>
<a
href={"https://www.cnn.com/"}
target={"_blank"}
rel={"noopener noreferrer"}
>
Read More on CNN
</a>
</div>
</section>
);
}
Your application is having 2 return which is wrong and hard approach. The easy way is to do condition rendering .The code below does it.