Component:
const postState = useSelector((state: RootState) => state.postsSlice.posts);
{
postState?.map((post) => {
return (
<PostCard
key={post.id}
title={post.title}
description={post.body}
user={post.user}
voteCount={post.upvotes - post.downvotes}
onClick={() => navigate(`/posts/${subredditId}/post/${post.id}`)}
/>
);
});
}
I am working on a reddit clone project with react typescript. I take the data from the api as an array of objects of the type:
export type Posts = Post[];
export type Post = {
id: string;
title: string;
user: string;
body: string;
upvotes: number;
downvotes: number;
};
And then I store the data in redux toolkit like this:
type PostsArray = {
posts: Array<Post>;
};
const initialState: PostsArray = { posts: [] };
const PostsSlice = createSlice({
name: "PostsSlice",
initialState: initialState,
reducers: {
setPostsData(state, action: PayloadAction<Array<Post>>) {
state.posts = action.payload;
},
},
});
export const { setPostsData } = PostsSlice.actions;
export default PostsSlice.reducer;
when I map the objects in my component I show the reddit vote count by subtracting downvotes from upvotes. What I want to do is being able to upvote and downvote different posts and store that vote in redux. I thought about a dispatch that increase the upvotes and a dispatch that increase the downvotes. But I cant figure it out how to do it. I dont know how to acces the upvotes of a specific post in redux. Any ideas?