I'm messing around practicing concepts using react, react-router6, & redux-toolkit. Here is a quick YT short showing the problem: https://www.youtube.com/shorts/jwidQfibVEo
Here is the Post.js file that contains the logic for getting a post
import React, { useEffect } from 'react'
import { useNavigate, useParams } from 'react-router-dom'
import jwtDecode from 'jwt-decode';
import { useSelector, useDispatch } from 'react-redux';
import { getPostAsync, postsSelector, deletePostAsync } from '../redux/slices/postSlice';
const Post = () => {
const { post } = useSelector(postsSelector);
const { postId } = useParams();
const navigate = useNavigate();
const dispatch = useDispatch();
useEffect(() => {
dispatch(getPostAsync(postId));
**where the console.logs in the video come from**
console.log(post);
}, [dispatch, postId]);
const handleDelete = () => {
dispatch(deletePostAsync(postId));
navigate('/posts')
}
const handleUpdate = () => {
navigate(`/posts/${postId}/update-post`)
}
//decode the token to get the username property off it to assign as a post's author
const token = localStorage.getItem('user');
const decode = jwtDecode(token);
return (
<div>
<h1>{post.title}</h1>
<h2>{post.body}</h2>
<p>Author: {post.author}</p>
{decode._id === post.user_id &&
<div className='button-group'>
<button onClick={handleDelete}>Delete</button>
<button onClick={handleUpdate}>Update</button>
</div>}
</div>
)
}
export default Post
Here is the initial state portion of the redux file
export const postSlice = createSlice({
name: 'posts',
initialState: {
posts: [],
post: {},
loading: false,
error: false
}
Here is the logic in redux setting the payload to the state for a post
getPost: (state, action) => {
state.post = action.payload;
}
Here is the logic for making a GET request for a api/posts/:postId route that sets the data as the payload for the state using getPost()
export const getPostAsync = (postId) => async (dispatch) => {
try {
const response = await axiosWithAuth().get(`api/posts/${postId}`);
dispatch(getPost(response.data));
} catch (error) {
dispatch(setError(error));
}
}