Home > other >  I have an error when using returning data from state in redux
I have an error when using returning data from state in redux

Time:09-27

When I try to update any post it return an array inside array like this

((3) [{…}, Array(3), Array(3)])

which is the first post and the same array two times so when I render the posts after updating one post only the updated post is showing

this is the code to dispatch the action

export const updatePost =(id, post) => async (dispatch) => {
try {
    const {data}  = await api.updatePost(id, post)
    dispatch({type:'UPDATE',payload:data})
    // console.log(data)

} catch (error) {
    console.log(error.mesage)
    
}

}

and this is the action

export default (posts=[],action) =>{
switch (action.type) {
    case 'FETCH_ALL':
        return action.payload
    case 'CREATE':
        return [...posts, action.payload]
    case 'LikePost':
    case 'UPDATE':
            // return [...posts, action.payload]
          return  posts.map(post => post._id===action.payload._id ? action.payload : posts)
    case 'DELETE':
        return posts.filter((post)=> post._id!==action.payload)
  

    default:
        return posts
} }

This is the reducer

import { combineReducers } from "redux";
import posts from './Posts'
export default  combineReducers({posts})

and here is how I fetch the data from redux state

 import { Grid, CircularProgress } from '@material-ui/core';
 import { useSelector } from 'react-redux';

 import Post from './Post/Post';
 import useStyles from './Styles';

const Posts = ({ setCurrentId }) => {
const posts = useSelector((state) => state.posts);
const classes = useStyles();

return (
 !posts.length ? <CircularProgress /> : (
   <Grid className={classes.container} container alignItems="stretch" spacing={3}>
     {posts.map((post) => (
       <Grid key={post._id} item xs={12} sm={6} md={6}>
         <Post post={post} setCurrentId={setCurrentId} />
       </Grid>
     ))}
   </Grid>
 )
);
};

export default Posts;


CodePudding user response:

The problem is in your action; you are creating this nested array yourself in this line:

return posts.map(post => {
  post._id === action.payload._id ? // if this is the post
    action.payload :                // use updated data
    posts                           // --error--: copy entire posts array
})

so, for every element that isn't the post being updated, you are replacing it with the entire posts array. If you want to use this pattern just replace posts with post:

return posts.map(post => post._id === action.payload._id ? action.payload : post)
  • Related