Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import React, { Component, useState, useEffect } from 'react'
- import PropTypes from 'prop-types'
- import { connect } from 'react-redux'
- import { fetchPosts } from '../actions/postActions'
- const Posts = props => {
- const [ mounted, setMounted ] = useState( false )
- const [ newPost, setNewPost ] = useState( false )
- if( ! mounted ) props.fetchPosts()
- useEffect( () => { setMounted( true ) }, [] )
- useEffect( () => {
- setNewPost( props.posts.unshift( props.newPost ) )
- }, [ props.newPost ] )
- const postItems = props.posts.map( post => (
- <div key={ post.id }>
- <h3>{ post.title }</h3>
- <p>{ post.body }</p>
- </div>
- ) )
- return(
- <div>
- <h1>Posts</h1>
- { postItems }
- </div>
- )
- }
- Posts.propTypes = {
- fetchPosts: PropTypes.func.isRequired,
- posts: PropTypes.array.isRequired,
- newPost: PropTypes.object
- }
- const mapStateToProps = state => ( {
- posts: state.posts.items,
- newPost: state.posts.item
- } )
- export default connect( mapStateToProps, { fetchPosts } )( Posts );
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement