Reputation: 191
I got a key error after entering a comment. But I can't find a reason.
Problem: Screen flashes after comment I get a key error and can't figure out where the key error is.
Here's how I tried to fix the key error:
key = {c} => key = {c.id}
What causes a key error?
error message is this:
VM152 _app.js:22355 Uncaught TypeError: Cannot read property 'key' of undefined
at List._this.renderItem (VM152 _app.js:22355)
at VM152 _app.js:22465
at Array.map (<anonymous>)
at List._this.renderList (VM152 _app.js:22464)
...
code is this
const Home = () => {
const dispatch = useDispatch();
const { isLoggedIn, me } = useSelector(state => state.user);
const { mainPosts } = useSelector(state => state.post);
useEffect(() => {
// alert("LOAD_MAIN_POSTS_REQUEST 실행")
dispatch({
type: LOAD_MAIN_POSTS_REQUEST,
})
}, []);
return (
<>
{me && <PostForm />}
{mainPosts.map((c) => {
return (
<PostCard key={c.id} post={c} />
);
})}
</>
);
};
Upvotes: 0
Views: 66
Reputation: 21
The first time the Home component renders the mainPosts array may not have any data, after useEffect is called and your action is dispatched the data will be present. To account for the data not being there on intial render you can validate mainPosts to check for null or undefined. That way the .map will only take place when mainPosts is truthy.
Upvotes: 1