Advertisement
Uno-Dan

Functional Component

Mar 27th, 2021
1,152
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import React, { Component, useState, useEffect } from 'react'
  2. import PropTypes from 'prop-types'
  3. import { connect } from 'react-redux'
  4. import { fetchPosts } from '../actions/postActions'
  5.  
  6. const Posts = props => {
  7.   const [ mounted, setMounted ] = useState( false )
  8.   const [ newPost, setNewPost ] = useState( false )
  9.  
  10.   if( ! mounted ) props.fetchPosts()
  11.  
  12.   useEffect( () => { setMounted( true ) }, [] )
  13.  
  14.   useEffect( () => {
  15.     setNewPost( props.posts.unshift( props.newPost ) )
  16.   }, [ props.newPost ] )
  17.  
  18.   const postItems = props.posts.map( post => (
  19.     <div key={ post.id }>
  20.       <h3>{ post.title }</h3>
  21.       <p>{ post.body }</p>
  22.     </div>
  23.   ) )
  24.  
  25.   return(
  26.     <div>
  27.       <h1>Posts</h1>
  28.       { postItems }
  29.     </div>
  30.   )
  31. }
  32.  
  33. Posts.propTypes = {
  34.   fetchPosts: PropTypes.func.isRequired,
  35.   posts: PropTypes.array.isRequired,
  36.   newPost: PropTypes.object
  37. }
  38.  
  39. const mapStateToProps = state => ( {
  40.   posts: state.posts.items,
  41.   newPost: state.posts.item
  42. } )
  43.  
  44. export default connect( mapStateToProps, { fetchPosts } )( Posts );
  45.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement