Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using React to render flash messages from Express

I've searched around a lot but have been unable to find a simple way to get flash messages from Express and render them in React.

I need to access the data on my Express server, but what is the best way of storing this and passing it down to React? I was thinking of passing an object down when the React index.html file is rendered, but I'm not sure how I can access this data, or send the correct data when certain events happen, for example a user enters the wrong password.

like image 442
HPJM Avatar asked Nov 18 '25 20:11

HPJM


1 Answers

I solved the issue.

I simply have a variable in my session called flash which is set to false by default.

In the correct part of the passport flow I redefine this to a string, depending on the error. I have a React action and reducer to get this data and if it's truthy, render it to the screen. When the component unmounts or the site is refreshed I reset it to false.

EDIT: I have found a better solution

1. In the passport middleware set an optional message if something goes wrong.

return done(null, false, { message: 'Email not found' });

2. In the login route send this information as a response.

router.post('/login', (req, res, next) => {

    passport.authenticate('local-login', (e, user, info) => {
        if(e) return next(e);
        if(info) return res.send(info);
        req.logIn(user, e => {
            if(e) return next(e);
            return res.send(user);
        });
    })(req, res, next);
});

3. Handle the submission and response in a Redux action generator. If the user authenticates, then the message property will be undefined.

const res = await axios.post('/auth/login', { email, password });

dispatch({
    type: 'FLASH',
    payload: res.data.message
});

4. In the reducer, the state will be either a string or false:

return action.payload || false;

5. Then it's a question of rendering the state to the screen. Another action can be sent when the component unmounts to reset the state.

Hope this helps someone else out there.

like image 139
HPJM Avatar answered Nov 21 '25 09:11

HPJM