I use mapStateToProps
to display a notification message:
function TabPanel(props) {
{props.webSocketMessage ? (<Typography className={classes.invalidLabel} color="textSecondary">Successful { props.webSocketMessage}</Typography>) : "" }
const mapStateToProps = state => ({
webSocketMessage: state.webSocketMessage
});
}
The code works but I would like to hide the message after 30 seconds.
How I can implement this functionality?
CodePudding user response:
Typically, (not with Redux) it would be handled in whatever parent component is passing webSocketMessage
as a prop to this component. Assuming you're storing the message as state in the parent, it may be something like...
import React, {useEffect, useState} from 'react';
const ParentComponent = () => {
const [webSocketMessage, setWebSocketMessage] = useState()
useEffect(() => {
if (webSocketMessage){
setTimeout(() => setWebsocketMessage(null), 30000)
}
}, [webSocketMessage])
return <ChildComponent webSocketMessage={webSocketMessage} />
}
export default ParentComponent;
This same idea can be turned into a redux action for clearing the message, since you're using the redux store to save that message. The basic idea is whatever is responsible for sending that prop (in your case Redux) also needs to be responsible for clearing it, so you end up with...
const clearMessage = () => dispatch({type: 'CLEAR_MESSAGE'})
dispatch({type: 'CLEAR_MESSAGE'})
can then be used in your reducer to set the messages in the state to null
, an empty array, or whatever you need.
Your message reducer may look like:
export function messageReducer(state = [], action) {
switch(action.type){
case 'ADD_MESSAGE':
return [...state, action.errorMessage]
case 'CLEAR_MESSAGES':
return []
default:
return state
}
}
as long as you already have some sort of message reducer being used by your root reducer, you should be able to just add that case to the switch statement.
Finally, in the component this snippet is taken from you can have something like...
useEffect(() => {
setTimeout(props.clearMessages, 30000)
}
and ultimately
const Whatever = () => {
// code
useEffect(() => {
setTimeout(props.clearMessages, 30000)
}
//other code
}
const mapStateToProps = (state) => {
return {
webSocketMessage: state.webSocketMessage
}
}
const mapDispatchToProps = (dispatch) => {
return {
clearMessages: () => dispatch({type: 'CLEAR_MESSAGES'})
}
}
export default connect(mapStateToProps, mapDispatchToProps)(Whatever);