fj785 fj785 -4 years ago 73
React JSX Question

New to React. Creating an app that authenticates users using Passport+cookies and my state gets lost on refresh

Reducer



<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
import {
LOGIN_USER_SUCCESS
} from '../actions/types';

const INITIAL_STATE = {
error: '',
message: '',
content: '',
authenticated: false,
authenticating: false,
username: '',
fullName: '',
password: '',
};

export default function(state = INITIAL_STATE, action) {
console.log('anything?');
switch (action.type) {
case LOGIN_USER_SUCCESS:
console.log(';', action.fullName);
console.log(';;', action);
console.log(state.fullName)
return {
...state,
fullName: action.fullName,
username: action.username,
password: action.password,
authenticating: false,
authenticated: true,
};
return state;
}




Action creator



<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

import {
LOGIN_USER_SUCCESS,
} from './types';

import axios from 'axios';
import cookie from 'react-cookie';
import Cookies from 'universal-cookie';
const cookies = new Cookies();

const API_URL = 'http://localhost:3001/api';

export const loginUser = (username, password) => {
return function(dispatch) {
axios
.post(`${API_URL}/auth/login`, { username, password })
.then(response => {
cookies.set('token', response.data.token, { path: '/' });
cookies.set('user', response.data.user, { path: '/' });
console.log(cookies.get('user'));
console.log(username);
dispatch({
type: LOGIN_USER_SUCCESS,
fullName: response.data.user.fullName,
});
setTimeout(
function() {
//window.location.href = 'http://localhost:3000/auth/dashboard';
},
3000
);
});

};
};





How do I keep my state from getting lost when redirecting from page to page? It seems like when I run window.location.href my page refreshes which seems to be causing the problem.

Answer Source

The answer is don't do that. Refresh in react always results in complete state loss, since your script stops running, page gets reloaded and script started again from initial fresh state.

Quite often login scenarios are implemented by issuing ajax call to get credentials, and when that credentials arrive they get stored in the state.

After that your components would recognize that credentials are present, and your components would display content instead of login.

Such scenarios are often implemented by using react partnering libraries like redux and react router.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download