Reputation: 87
I'm trying to make it possible to like a post, and allow it update without re rendering the page.
The following code allows a user to like a post, but only on refresh i am able to see the updated like count.
the likes is from the mapped Posts Array
like this
and i get the number of likes on a post like this likes.length
<Like like={id} likes={Likes.length} />
how would i be able to update the number of likes when this action is called
export const postLike = (id) => {
return (dispatch) => {
// console.log(userId);
return Axios.post('/api/posts/like', {
postId: id
}).then( (like) => {
dispatch({type: ADD_LIKE, id})
// console.log('you have liked this', like)
}).catch( (err)=> {
console.log('there seem to be an error', err);
})
}
}
export const GetPosts = () => {
return (dispatch, getState) => {
return Axios.get('/api/posts/myPosts')
.then( (res) => {
const data = res.data
const likes = res.data[0].Likes // gets the first item within array, and shows likes. I would need to get all posts likes not just the first item
console.log(likes); // logs data and i can see an array
dispatch({type: GET_POSTS, data})
})
}
}
the following code doesn't work, i have to refresh the page to see the updated number of likes.
How would i be able to convert Likes.lenght into a state, so that it can automatically update onClick like from the Like Component ?
I do know that likes:0 does not get the value of likes for each post. How would i make this possible ?
reducer
import { ADD_LIKE} from '../actions/';
const initialState = {
post: [],
postError: null,
posts:[],
isEditing:false,
isEditingId:null,
likes:0,
postId:null
}
export default (state = initialState, action) => {
switch (action.type) {
case GET_POSTS:
return {
...state,
posts: action.data
}
case ADD_LIKE:
console.log(action.id) // renders post id which is 2
console.log(state.posts) // logs posts array
return {
...state,
posts: state.posts.map(post => {
if (post.id === action.id) {
return {
...post,
likes: post.likes + 1
}
} else return post
})
};
case GET_LIKES_COUNT:
console.log(action.data) // logs number of likes for all posts
console.log(state.posts) // logs an array of posts
console.log(action.id) // logs post id
// need to check if post.id is === action.id if so give it the value from action.data
return({
...state,
likes: action.data
})
PostItem Component
import React, { Component } from 'react';
import Paper from '@material-ui/core/Paper';
import Button from '@material-ui/core/Button';
import Typography from '@material-ui/core/Typography';
import moment from 'moment';
import Editable from './Editable';
import {connect} from 'react-redux';
import {UpdatePost, postLike} from '../actions/';
import Like from './Like';
import Axios from '../Axios';
const Styles = {
myPaper: {
margin: '20px 0px',
padding: '20px'
},
button:{
marginRight:'30px'
}
}
class PostItem extends Component{
constructor(props){
super(props);
this.state = {
disabled: false,
myId: 0,
likes:0
}
}
onUpdate = (id, title) => () => {
// we need the id so expres knows what post to update, and the title being that only editing the title.
if(this.props.myTitle !== null){
const creds = {
id, title
}
this.props.UpdatePost(creds);
}
}
render(){
const {title, id, userId, removePost, createdAt, post_content, username, editForm, isEditing, editChange, myTitle, postUpdate, Likes, clickLike} = this.props
return(
<div>
<Typography variant="h6" component="h3">
{/* if else teneray operator */}
{isEditing ? (
<Editable editField={myTitle ? myTitle : title} editChange={editChange}/>
): (
<div>
{title}
</div>
)}
</Typography>
<Typography component="p">
{post_content}
<h5>
by: {username}</h5>
<Typography color="textSecondary">{moment(createdAt).calendar()}</Typography>
<Like like={id} likes={Likes.length} />
</Typography>
{!isEditing ? (
<Button variant="outlined" type="submit" onClick={editForm(id)}>
Edit
</Button>
):(
// pass id, and myTitle which as we remember myTitle is the new value when updating the title
<div>
<Button
disabled={myTitle.length <= 3}
variant="outlined"
onClick={this.onUpdate(id, myTitle)}>
Update
</Button>
<Button
variant="outlined"
style={{marginLeft: '0.7%'}}
onClick={editForm(null)}>
Close
</Button>
</div>
)}
{!isEditing && (
<Button
style={{marginLeft: '0.7%'}}
variant="outlined"
color="primary"
type="submit"
onClick={removePost(id)}>
Remove
</Button>
)}
</div>
)
}
}
const mapStateToProps = (state) => ({
isEditingId: state.post.isEditingId
})
const mapDispatchToProps = (dispatch) => ({
// pass creds which can be called anything, but i just call it credentials but it should be called something more
// specific.
UpdatePost: (creds) => dispatch(UpdatePost(creds)),
postLike: (id) => dispatch( postLike(id))
// Pass id to the DeletePost functions.
});
export default connect(null, mapDispatchToProps)(PostItem);
Like Component
import React, { Component } from 'react';
import ReactDOM from 'react-dom'
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faCoffee, faAdjust } from '@fortawesome/free-solid-svg-icons';
import {connect} from 'react-redux';
import { postLike} from '../actions/';
class Like extends Component{
constructor(props){
super(props);
this.state = {
likes: null,
heart: false
}
}
clickLike = (id) => {
this.props.postLike(id);
// toggles between css class
this.setState({
heart: !this.state.heart
})
}
render(){
return(
<div style={{float:'right', fontSize: '1.5em', color:'tomato'}} >
<i style={{ marginRight: '140px'}} className={this.state.heart ? 'fa fa-heart':'fa fa-heart-o' }>
<span style={{ marginLeft: '6px'}}>
<a href="" onClick={ () => this.clickLike(this.props.like)}>Like</a>
<span style={{ marginLeft: '7px'}} >
// gets likes
{this.props.likes}
</span>
</span>
</i>
</div>
)
}
}
const mapStateToProps = (state) => ({
isEditingId: state.post.isEditingId,
likeCount:state.post.likes
})
const mapDispatchToProps = (dispatch) => ({
postLike: (id) => dispatch( postLike(id))
// Pass id to the DeletePost functions.
});
export default connect(mapStateToProps, mapDispatchToProps)(Like);
Upvotes: 0
Views: 293
Reputation: 5472
Looks to me like you have a naming discrepancy. likes
in your reducer is defined with a lowercase l
, but your code is expecting uppercase (from what I can make out in your console log and GetPosts
action).
case ADD_LIKE:
console.log(action.id) // renders post id which is 2
console.log(state.posts) // logs posts array
return {
...state,
posts: state.posts.map(post => {
if (post.id === action.id) {
return {
...post,
// likes: post.likes + 1
Likes: post.Likes + 1
}
} else return post
})
};
Upvotes: 1