Skip to main content

React-Redux most recently POSTed object is always undefined until I refresh

So I'm working with react and redux to make a simple blog app where you fill out a form and onSubmit that data is added to a grid of other posts. However, when I use the useSelector() method to gather the state, the most recently POST'd object is always undefined, even though it properly makes it through redux. Here's the flow:

From Form:

const handleSubmit = (e) => {
        e.preventDefault()
        console.log("FORM DATA:")
        console.log(postData);
        dispatch(createPost(postData));
    }

Here's the action dispatched:

export const createPost = (post) => async (dispatch) => {
    try 
    {
        const data = await api.createPost(post);
        console.log("ACTION DATA:");
        console.log(data.data);
        dispatch({ type: "CREATE", payload: data.data});
    } 
    catch (error) 
    {
        console.log(error.message);
    }
}

Here is the reducer associated with the action, with the case being 'CREATE':

export default (posts = [], action) => {
    switch (action.type) {
        case "FETCH_ALL":
            return action.payload;
        case "CREATE":
            console.log("REDUCER DATA:")
            console.log(action.payload);
            return [...posts, action.paylaod];
        default:
            return posts;
    }
}

Here's my component that dynamically renders the posts:

const Posts = () => {
    const classes = useStyles();
    const getState = useSelector((state) => {
        return state;
    })
    const posts = getState.posts;
    console.log(posts);
    return (
        !posts.length ? <CircularProgress /> : (
          <Grid className={classes.container} container alignItems="stretch" spacing={3}>
            {posts.map((post, index) => (
              <Grid key={index} item xs={12} sm={6} md={6}>
                <Post post={post}/>
              </Grid>
            ))}
          </Grid>
        )
      );
    
}

Above is where I first noticed the error. When I submit the form, the console log just after the useSelector() methods returns the array of post objects, however the one that I just added is ALWAYS undefined. This means I run into an error trying to render a post because the object can't be read as it's undefined:

const Post = ({ post }) => {
    const classes = useStyles();

    
    return (
        <Card className={classes.card}>
            <CardMedia className={classes.media} image={'https://user-images.githubusercontent.com/194400/49531010-48dad180-f8b1-11e8-8d89-1e61320e1d82.png'} title={post.title}/>
            <div className={classes.overlay}>
                <Typography variant='h6'>{post.creator}</Typography>
                <Typography variant='body2'>{moment(post.createdAt).fromNow()}</Typography>
            </div>
            <div className={classes.overlay2}>
                <Button style= size="small" onClick={() => {}}>
                    <MoreHorizIcon fontSize="medium"/>
                </Button>
            </div>
            <div className={classes.details}>
                <Typography variant="body2" color="textSecondary">{post.tags.map((tag) => `#${tag} `)}</Typography>
            </div>
            <Typography className={classes.title} gutterBottom variant="h5" component="h2">{post.title}</Typography>
            <CardContent>
                <Typography variant="body2" color="textSecondary" component="p">{post.message}</Typography>
            </CardContent>
            
        </Card>
     );
}

I immediately run into an issue here trying to read post.title, post.message, etc... as it's all undefined. The only way I've managed to get this to work is to remove e.preventDefault() from the form submit, which works but I'd rather have it all render without having to refresh. What am I missing here? And why would the refresh have any effect on this?

console.log of state after I submit the form:

(10) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, undefined]
0: {_id: '61cd4ebc0a9d0366a8b59fda', title: 'Disney', message: 'message', creator: 'Logan', tags: Array(1), …}
1: {_id: '61cdf29e0a9d0366a8b5a016', title: 'San Diego', message: 'with cousins', creator: 'Logan', tags: Array(1), …}
2: {_id: '61cdf5e00a9d0366a8b5a03f', title: '', message: '', creator: '', tags: Array(1), …}
3: {_id: '61cdf6190a9d0366a8b5a043', title: '', message: '', creator: '', tags: Array(1), …}
4: {_id: '61cdf7e50a9d0366a8b5a047', title: 'll', message: 'llll', creator: 'l', tags: Array(1), …}
5: {_id: '61cdfea1c6f7be0a79b7320f', title: '', message: '', creator: '', tags: Array(1), …}
6: {_id: '61cdfec1c6f7be0a79b73212', title: '', message: '', creator: '', tags: Array(1), …}
7: {_id: '61cdff8ac6f7be0a79b73216', title: '', message: '', creator: '', tags: Array(1), …}
8: {_id: '61cdffc3c6f7be0a79b7321b', title: '', message: '', creator: '', tags: Array(1), …}
9: undefined
length: 10
[[Prototype]]: Array(0)

And after a refresh:

(10) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
0: {_id: '61cd4ebc0a9d0366a8b59fda', title: 'Disney', message: 'message', creator: 'Logan', tags: Array(1), …}
1: {_id: '61cdf29e0a9d0366a8b5a016', title: 'San Diego', message: 'with cousins', creator: 'Logan', tags: Array(1), …}
2: {_id: '61cdf5e00a9d0366a8b5a03f', title: '', message: '', creator: '', tags: Array(1), …}
3: {_id: '61cdf6190a9d0366a8b5a043', title: '', message: '', creator: '', tags: Array(1), …}
4: {_id: '61cdf7e50a9d0366a8b5a047', title: 'll', message: 'llll', creator: 'l', tags: Array(1), …}
5: {_id: '61cdfea1c6f7be0a79b7320f', title: '', message: '', creator: '', tags: Array(1), …}
6: {_id: '61cdfec1c6f7be0a79b73212', title: '', message: '', creator: '', tags: Array(1), …}
7: {_id: '61cdff8ac6f7be0a79b73216', title: '', message: '', creator: '', tags: Array(1), …}
8: {_id: '61cdffc3c6f7be0a79b7321b', title: '', message: '', creator: '', tags: Array(1), …}
9: {_id: '61ce01d5c6f7be0a79b7321e', title: '', message: '', creator: '', tags: Array(1), …}
length: 10
[[Prototype]]: Array(0)
Via Active questions tagged javascript - Stack Overflow https://ift.tt/2FdjaAW

Comments

Popular posts from this blog

Where and how is this Laravel kernel constructor called? [closed]

Where and how is this Laravel kernel constructor called? public fucntion __construct(Application $app, $Router $roouter) { } I have read the documentation and some online tutorial but I can find any clear explanation. I am learning Laravel and I am wondering where does this kernel constructor receives its arguments from. "POSTMOTERM" CLARIFICATION: Here is more clarity.I have checked the boostrap/app.php and it is only used for boostrapping the interfaces into the container class. What is not clear to me is where and how the Kernel class is instatiated and the arguments passed to the object calling the constructor.Something similar to; obj = new kernel(arg1,arg2) or, is the framework using some magic functions somewhere? Special gratitude to those who burn their eyeballs and brain cells on this trivia before it goes into a full blown menopause alias "MARKED AS DUPLICATE". To some of the itchy-finger keyboard warriors, a.k.a The mods,because I believe in th...

Why is my reports service not connecting?

I am trying to pull some data from a Postgres database using Node.js and node-postures but I can't figure out why my service isn't connecting. my routes/index.js file: const express = require('express'); const router = express.Router(); const ordersCountController = require('../controllers/ordersCountController'); const ordersController = require('../controllers/ordersController'); const weeklyReportsController = require('../controllers/weeklyReportsController'); router.get('/orders_count', ordersCountController); router.get('/orders', ordersController); router.get('/weekly_reports', weeklyReportsController); module.exports = router; My controllers/weeklyReportsController.js file: const weeklyReportsService = require('../services/weeklyReportsService'); const weeklyReportsController = async (req, res) => { try { const data = await weeklyReportsService; res.json({data}) console...

How to show number of registered users in Laravel based on usertype?

i'm trying to display data from the database in the admin dashboard i used this: <?php use Illuminate\Support\Facades\DB; $users = DB::table('users')->count(); echo $users; ?> and i have successfully get the correct data from the database but what if i want to display a specific data for example in this user table there is "usertype" that specify if the user is normal user or admin i want to user the same code above but to display a specific usertype i tried this: <?php use Illuminate\Support\Facades\DB; $users = DB::table('users')->count()->WHERE usertype =admin; echo $users; ?> but it didn't work, what am i doing wrong? source https://stackoverflow.com/questions/68199726/how-to-show-number-of-registered-users-in-laravel-based-on-usertype