connect-flash icon indicating copy to clipboard operation
connect-flash copied to clipboard

Wrong example checking for message

Open ePirat opened this issue 11 years ago • 2 comments

The examples show that this if (message) { is the proper way to check if a message is there, actually this will be true every time, even if no message is set. It seems to work with:

if (message.length !== 0) {

I am not sure, but it seems that message, when empty is an empty object ({}) so checking for it will be true in any case.

ePirat avatar Aug 26 '14 22:08 ePirat

I think it always returns array.

pronebird avatar Oct 28 '14 13:10 pronebird

Same here. If in your route or render method you set messages variable like

messages: req.flash()

Then you will get a messages variable in the rendered view which will be eqal to

{[]}

because req.flash() will still create an empty array.

So yes in your view you will need to check the length is not 0

I made a partial for flash messages that checks for both the existence and the length so I can include it at the top of all views

<% if(typeof messages !== 'undefined') { %>
<% if (typeof messages.error !== 'undefined' && messages.error.length > 0) { %>
    <p class="error"><%= messages.error %></p>
<% } %>
<% if (typeof messages.info !== 'undefined' && messages.info.length > 0) { %>
    <p class="info"><%= messages.info %></p>
<% } %>
<% if (typeof messages.success !== 'undefined' && messages.success.length > 0) { %>
    <p class="info"><%= messages.success %></p>
<% } %>
<% } %>

For ejs templates at top of body

<% include partials/flash.server.partial.html %>

This way I can just use req.flash() in my render function and every view will check for the existence of the 3 types of error messages I might or might not have flashed at some point in the process.

isimmons avatar Jul 06 '15 18:07 isimmons