Using Rails backend and React frontend, a user can comment on a post and can like/unlike a post. Everything works as intended but when I am on the PostDetail.js, and I refresh the page, I get an error message.
PostDetail.js:27 Uncaught TypeError: Cannot read properties of undefined (reading 'id')
at PostDetail (PostDetail.js:27:1)
at renderWithHooks (react-dom.development.js:16305:1)
at mountIndeterminateComponent (react-dom.development.js:20074:1)
at beginWork (react-dom.development.js:21587:1)
at HTMLUnknownElement.callCallback (react-dom.development.js:4164:1)
at Object.invokeGuardedCallbackDev (react-dom.development.js:4213:1)
at invokeGuardedCallback (react-dom.development.js:4277:1)
at beginWork$1 (react-dom.development.js:27451:1)
at performUnitOfWork (react-dom.development.js:26557:1)
at workLoopSync (react-dom.development.js:26466:1)
The above error occurred in the component: at PostDetail (http://localhost:4000/main.392f23b132859f3bd7ac.hot-update.js:41:56) at RenderedRoute (http://localhost:4000/static/js/bundle.js:41906:5) at Routes (http://localhost:4000/static/js/bundle.js:42538:5) at div at Router (http://localhost:4000/static/js/bundle.js:42476:15) at BrowserRouter (http://localhost:4000/static/js/bundle.js:40582:5) at App at ContentProvider (http://localhost:4000/static/js/bundle.js:1145:3) at UserProvider (http://localhost:4000/static/js/bundle.js:1335:3) at ErrorProvider (http://localhost:4000/static/js/bundle.js:1256:3) Consider adding an error boundary to your tree to customize error-handling behavior. Visit https://reactjs.org/link/error-boundaries to learn more about error boundaries.
Here are my codes:
function PostDetail () {
const { setErrors } = useContext(ErrorContext);
const { user } = useContext(UserContext);
const { contents, deletePost } = useContext(ContentContext);
const postId = parseInt(useParams().id);
const post = contents.find(post => post.id === postId);
const navigate = useNavigate();
const [commentMode, setCommentMode] = useState(false);
const openComment = () => setCommentMode(commentMode => !commentMode);
const [liked, setLiked] = useState(false);
const params = useParams();
useEffect(() => {
fetch(`/posts/${post.id}/likes`)
.then(resp => resp.json())
.then(data => {
setLiked(data.liked);
})
.catch(error => setErrors(error))
}, [post.id, setErrors])
It is saying that it cannot read the property of the id in }, [post.id, setErrors])
Maybe you missing a '{}' in the catch(error.. ? Cause I see it return setErrors?