I am attempting to create my own alert component using react (also in this case, Bootstrap v4). Basically, if something happens which the user needs to be notified of, create a message, put it in the store and have react render the alert. I know what I am doing should be possible, however I am new enough to react that there is something I am missing/don't understand about how react works which is causing no alerts to be displayed.
Firstly, I alerts to be available to all other components, so I put it in my app.js
:
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { PersistGate } from 'redux-persist/integration/react';
import AppRouter from './routers/AppRouter';
import configureStore from './store/configureStore';
import Alerts from './components/controls/Alerts';
const { store, persistor } = configureStore();
const jsx = (
<Provider store={store}>
<PersistGate loading={null} persistor={persistor}>
<Alerts />
<AppRouter />
</PersistGate>
</Provider>
);
ReactDOM.render(jsx, document.getElementById('root'));
Next are the components for Alerts
. First the actions:
// DISPLAY_ALERT
export const displayAlert = (message, severity) => ({
type: 'DISPLAY_ALERT',
message: message,
severity: severity
});
// DISMISS_ALERT
export const dismissAlert = (id) => ({
type: 'DISMISS_ALERT',
id: id
});
The reducer:
const alertsDefaultState = [];
const alertNotify = (state, action) => {
let queue = state;
if (!queue || !Array.isArray(queue))
queue = [];
let newAlert = {
id: getUniqueId(),
message: action.message,
severity: action.severity
};
queue.push(newAlert);
return queue;
};
const alertDismiss = (state, action) => {
const newQueue = state.filter((element) => element.id !== action.id);
return newQueue;
};
const getUniqueId = () => {
return (Date.now().toString(36) + Math.random().toString(36).substr(2, 5)).toUpperCase();
};
export default (state = alertsDefaultState, action) => {
switch (action.type) {
case 'DISPLAY_ALERT':
return alertNotify(state, action);
case 'DISMISS_ALERT':
return alertDismiss(state, action);
case 'LOG_OUT_OF_API':
return [];
default:
return state;
}
};
The store:
import { createStore, combineReducers } from 'redux';
import { persistStore, persistReducer } from 'redux-persist';
import storage from 'redux-persist/lib/storage';
import alertsReducer from '../reducers/alerts';
export default () => {
const persistConfig = {
key: 'root',
storage,
};
let reducers = combineReducers({
// Other reducers
alerts: alertsReducer
});
let store = createStore(
persistReducer(persistConfig, reducers),
window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
);
let persistor = persistStore(store);
return { store, persistor };
};
And finally the Alerts
components:
import React from 'react';
import { connect } from 'react-redux';
import { dismissAlert } from '../../actions/alerts';
class Alerts extends React.Component {
constructor(props) {
super(props);
}
getAlerts = () => {
if (!this.props.alerts || this.props.alerts.length === 0)
return null;
const alertFixed = {
position:'fixed',
top: '0px',
left: '0px',
width: '100%',
zIndex: 9999,
borderRadius: '0px'
};
return (
<div style={alertFixed}>
{
this.props.alerts.map((alert) => {
const alertClass = `alert alert-${alert.severity} alert-dismissible m-4`
setTimeout(() => {
this.props.dispatch(dismissAlert(alert.id));
}, 5000);
return (
<div key={alert.id} id={alert.id} className={alertClass} role="alert">
<button type="button" className="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
{ alert.message }
</div>
);
}
)
}
</div>
);
}
render() {
return this.getAlerts()
}
}
const mapStateToProps = (state) => {
return {
alerts: state.alerts
}
};
export default connect(mapStateToProps)(Alerts);
One last thing, I have a const class for the types of alerts:
export default {
Info: 'info',
Success: 'success',
Warning: 'warning',
Error: 'danger',
};
If I run the above code and have something in the alerts store
, then it will be rendered. However, if I add something to the store on an event, such as a button click, I can see the alert being added to the store, but the component won't add it to the DOM.
What am I missing?
EDIT:
Arrays are reference type in Javascript
In your
const alertNotify = (state, action) => {
let queue = state;
if (!queue || !Array.isArray(queue))
queue = [];
let newAlert = {
id: getUniqueId(),
message: action.message,
severity: action.severity
};
queue.push(newAlert);
return queue;
};
Instead of doing something like this
let queue = state;
You need to make a copy of it (instead of referencing it) and then do
queue.push(newAlert);
i.e change your initial queue declaration to this (i am using spread operator to make copy of your passed state and then pushing newAlert in your queue
let queue = [...state];
Since your queue when returning, didn't had state in it
This condition was being fired
if (!this.props.alerts || this.props.alerts.length === 0)