3
votes

I am new to react. I have created a news component that consumes a json url then spits out some news articles. In the client side UI if the clients changes the json url it will update without refreshing the page using this code:

componentDidUpdate(prevProps) {
   if (prevProps.jsonUrl !== this.props.jsonUrl) {
       this.getPosts();
   }
}

However I also need the the news feed to update reactively if the postCount: this.props.postCount is changed in the client side UI. The post count is used in the render method below to choose how many posts to display.

posts
    .slice(0, postCount)
    .map(post => {
        // Variables to use
        let { id, name, summary, url, imgUrl} = post;
        // Stripping html tags from summary
        //let strippedSummary = summary.replace(/(<([^>]+)>)/ig,"");
        // What we actually render
        return (
            <div key={id} className={ styles.post}>
                <p>{name}</p>
                {/* <p>{summary}</p> */}
                <a href={url}>{url}</a>
                <img className={ styles.postImage} src={imgUrl} />
            </div>
        );
    })

Any help is much appreciated! - I was thinking something like this inside componentDidUpdate:

if (prevProps.postCount !== this.props.postCount) {
    this.setState( this.state.postCount; );
}

EDIT:

I am now using the postCount from the props instead of a state and it updates instantly! :D

// Grabbing objects to use from state
const { posts, isLoading } = this.state;
const { postCount } = this.props;
1

1 Answers

1
votes

The components are going to react automatically to the changes in their props, so there's no need to transfer any props to a state. In this case, if postCount is a prop, when it changes it should affect the piece of code that you shared to render the component. However, I don't know if posts is part of the state, in your case it should be and your method getPosts should setState with the new posts.