Reputation: 1593
This is the first time I am using react. I am coming from jQuery to React this feels like a big jump. If anybody can help me refactor this to work the React way I will be forever in your debt! :)
I am trying to parse an RSS feed, where I want to grab the most recent post title and link to render into a component.
https://www.npmjs.com/package/rss-parser - Using this to get the parser.
When viewing my app in the browser the async function is spitting out the rss feed into the console, which is a good start I guess!
// src/App/index.tsx
import * as React from 'react';
import * as Parser from 'rss-parser';
// Types
import { string } from 'prop-types';
let parser = new Parser();
// blueprint for the properties
interface Props {
name: string;
}
// Component state
interface State {
//feed: any[];
}
(async () => {
let feed = await parser.parseURL('https://www.reddit.com/.rss');
console.log(feed.title);
feed.items.forEach((item: { title: string; link: string; }) => {
console.log(item.title + ':' + item.link)
});
})();
export default class App extends React.Component<Props, State> {
render() {
return (
<div>
<h1>RSS Feed</h1>
<div>
<h1>item.title</h1>
<a href="">item.link</a>
</div>
</div>
);
}
}
Upvotes: 4
Views: 7937
Reputation: 328
I faced the same problem and solved by this. if you don't check for "undefined" value. It will show you error because react renders page 2 times and you have an undefined array of feed.items
in your hand when in first render.
My index.js file:
import React from 'react'
import {render} from 'react-dom';
let Parser = require('rss-parser');
let parser = new Parser();
const CORS_PROXY = "https://cors-anywhere.herokuapp.com/";
class App extends React.Component{
constructor(props) {
super(props);
this.state = {
feed: []
};
}
async componentDidMount() {
const feed = await parser.parseURL(CORS_PROXY + 'https://www.reddit.com/.rss');
this.setState(feed)
}
render() {
return (
<div>
<h1>Blog Posts</h1>
{this.state.items && this.state.items.map((items, i) => (
<div key={i}>
<h1>{items.title}</h1>
<a href="">{items.link}</a>
</div>
))}
</div>
);
}
}
render(
<App />,
document.getElementById("root")
)
Upvotes: 0
Reputation: 899
If I understand you right, you need something like this:
export default class App extends React.Component<Props, State> {
constructor(props: {}) {
super(props);
this.state = { feed: [] };
}
async componentDidMount() {
const feed = await parser.parseURL('https://www.reddit.com/.rss');
this.setState({ feed });
}
render() {
return (
<div>
<h1>RSS Feed</h1>
this.state.feed.map((item, i) => (
<div key={i}>
<h1>item.title</h1>
<a href="">item.link</a>
</div>
))
</div>
);
}
}
Upvotes: 7