-1
Hello, I’m new to the whole issue of React and Redux so I wanted a little help. I made a simple code:
home js.
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux'
import { authLoginSucesso, authLoginErro, authLogout } from '../../actions/auth.action';
class Home extends Component {
render() {
const { isAuth, authLoginSucesso, authLoginErro, authLogout } = this.props;
return (
<div className="container">
{
isAuth ? <div>Está autenticado</div>
: <div>Não está autenticado</div>
}
<button onClick={ () => authLoginSucesso() }>
Logar
</button>
<button onClick={ () => authLoginErro() }>
Erro logar
</button>
<button onClick={ () => authLogout() }>
LogOut
</button>
</div>
);
}
}
const mapStateToProps = store => ({
isAuth: store.auth.isAuth
});
const mapDispatchToProps = dispatch =>
bindActionCreators({ authLoginSucesso, authLoginErro, authLogout }, dispatch);
export default connect(mapStateToProps, mapDispatchToProps)(Home);
auth.action.js
export const authLoginSucesso = () => async dispatch => {
return dispatch({
type: 'AUTH_LOGIN_SUCESSO'
})
}
export const authLoginErro = () => async dispatch => {
return dispatch({
type: 'AUTH_LOGIN_ERRO'
})
}
export const authLogout = () => async dispatch => {
return dispatch({
type: 'AUTH_LOGOUT'
})
}
auth.reducer.js
const initialState = {
isAuth: false
};
export const authReducer = (state = initialState, action) => {
switch (action.type) {
case 'AUTH_LOGIN_SUCESSO':
return { isAuth: true };
case 'AUTH_LOGIN_ERRO':
return { isAuth: false };
case 'AUTH_LOGOUT':
return { isAuth: false };
default:
return state;
}
};
store js.
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import { rootReducers } from './rootReducers';
const initialValue = {}
export const Store = createStore(rootReducers, initialValue, applyMiddleware(thunk));
rootReducers.js
import { authReducer } from '../reducers/auth.reducer';
import { combineReducers } from 'redux';
export const rootReducers = combineReducers({
auth: authReducer
});
This was just to test how Redux would behave on a login screen, when the guy that logout, login successfully and Login fails.
But I noticed that the default state of isAuth
is false
then the component home.js
renders with the testo "Not authenticated", then I click on the "Log in" button, it changes the state to true, updates the store, the message changes to "Is authenticated" normally, but when I give F5 on the page, it starts the component as "Not authenticated"state returned to default value, should not cache data?
How do I store this data in the cache?