0

I have a problem when i refresh the page , the page automatically return false isLogin. i dont know, i already tried many times and ask to stackoverflow but no result. as we know . the browser will refresh the page if we try to edit the code and save it. and then wehen i try to console the props isloggin, when i login it return true, but whenn refresh the page, it return false. @.@

index.js

import React from "react";
import ReactDOM from "react-dom";
import { createStore } from 'redux'
import { Provider } from 'react-redux'
import { Router, Route, Switch} from "react-router-dom";
import { createHashHistory } from 'history';

import "assets/vendor/nucleo/css/nucleo.css";
import "assets/vendor/@fortawesome/fontawesome-free/css/all.min.css";
import "assets/scss/argon-dashboard-react.scss";

import AdminLayout from "layouts/Admin.js";
import reducer from './components/reducers'
import LandingLogin from './layouts/LandingLogin.js'
import LandingRegister from './layouts/LandingRegister.js'


const store = createStore(reducer);
const customHistory = createHashHistory();



ReactDOM.render(
  <Provider store = {store}>
      <Router history={customHistory}>
        <Switch>
          <Route path="/admin" render={props => <AdminLayout {...props} />} />
          <Route exact path="/" render= {() => <LandingLogin/>} />
          <Route exact path="/login" render= {() => <LandingLogin/>} />
          <Route exact path="/register" render= {() => <LandingRegister/>} />
        </Switch>
      </Router>
  </Provider>,
  document.getElementById("root")
);

login.js

import React, { Fragment } from 'react'
import { connect } from 'react-redux'
import { userLogin } from '../../actions/index'
import axios from 'axios';
import { createHashHistory } from 'history';

// reactstrap components
import {
  Button,
  Card,
  CardBody,
  FormGroup,
  Form,
  Input,
  InputGroupAddon,
  InputGroupText,
  InputGroup,
  Col
} from "reactstrap";

const customHistory = createHashHistory();

class Login extends React.Component {
    constructor(props) {
      super(props);
      this.state = {
        post : [],
        formData : {
          id : '',
          first_name : '',
          last_name : '',
          email : '',
          gender : '',
          password: '',
        },
        isLogedIn : true

      }
      this.handleForm = this.handleForm.bind(this);
      this.submitLogin = this.submitLogin.bind(this);
    }

    getPostAPI = () => {
      axios.get('http://localhost:8001/datauser')
      .then((res) => {
          this.setState ({
              post : res.data
          })
      })
    }

    getPostAPI2 = () => {
      axios.get('http://localhost:8001/dataadmin')
      .then((res) => {
          this.setState ({
              post : res.data
          })
      })
    }

    handleForm = (e) => {
      let formDataNew = {...this.state.formData};
      formDataNew[e.target.name] = e.target.value;
      this.setState({
        formData : formDataNew
      })

    }

    loadValues = () => {
      this.setState({
        formData: [`{"email": "${this.state.formData.email}","password": "${this.state.formData.password}"}`],
      }, () => {
        sessionStorage.setItem('formData', this.state.formData)
      })
    }

    submitLogin = (event) => {
      const { dispatch } = this.props;
      const {post} = this.state;    
      if(post.find(e =>  `${e.email}${e.password}` === `${this.state.formData.email}${this.state.formData.password}` )) {
        dispatch(userLogin(this.state.formData.email, this.state.formData.password));
        this.loadValues();
              customHistory.push('/admin/index');
      }else  {
        alert("Email atau Password Salah!");
        this.setState ({
          formData : {
            email : '',
            password: ''
          },


        })

      }
    }

    componentDidMount () {
      this.getPostAPI2();
    }

    render() {
        return (
            <Fragment>
              <Col lg="5" md="7">
                <Card className="bg-secondary shadow border-0">
                  <CardBody className="px-lg-5 py-lg-5">
                  <div className="text-center text-muted mb-4">
                      <h2>Form Login</h2>
                  </div>
                    <Form role="form">
                      <FormGroup className="mb-3">
                        <InputGroup className="input-group-alternative">
                          <InputGroupAddon addonType="prepend">
                            <InputGroupText>
                              <i className="ni ni-email-83" />
                            </InputGroupText>
                          </InputGroupAddon>
                          <Input onChange={this.handleForm} value={this.state.formData.email} name = "email" placeholder="Email" type="email" />
                        </InputGroup>
                      </FormGroup>
                      <FormGroup>
                        <InputGroup className="input-group-alternative">
                          <InputGroupAddon addonType="prepend">
                            <InputGroupText>
                              <i className="ni ni-lock-circle-open" />
                            </InputGroupText>
                          </InputGroupAddon>
                          <Input onChange={this.handleForm} value={this.state.formData.password} name = "password" placeholder="Password" type="password" />
                        </InputGroup>
                      </FormGroup>
                      <div className="custom-control custom-control-alternative custom-checkbox">
                        <input
                          className="custom-control-input"
                          id=" customCheckLogin"
                          type="checkbox"
                        />
                        <label
                          className="custom-control-label"
                          htmlFor=" customCheckLogin"
                        >
                          <span className="text-muted">Remember me</span>
                        </label>
                      </div>

                      <div className="text-center">
                        <Button onClick={this.submitLogin} className="my-4" color="primary" type="button">
                        Log in
                      </Button>
                      </div>
                    </Form>
                  </CardBody>
                </Card>
              </Col>

            </Fragment>
          );
        }
      }

      function select(state) {
        return {
          users: state.users
        }
      }

      export default connect(select)(Login);

reducers users.js



import { USER_LOGIN, USER_LOGOUT} from '../../constants/ActionTypes';


const initialState = {
    isLoggedIn: false
  }


export default function users(state = initialState, action) {
  switch (action.type) {
    case USER_LOGIN:
        return Object.assign({}, state, response(state, action));
    case USER_LOGOUT:
        return Object.assign({}, state, logout());

    default:
      return state
  }

function response(state){

  state.isLoggedIn = true;
  return state

}

function logout(){
    state.isLoggedIn = false;
    return state;
    }
}

actiontype.js

export const USER_LOGIN = 'USER_LOGIN'
export const USER_LOGOUT = 'USER_LOGOUT'

actions.js

import { USER_LOGIN, USER_LOGOUT} from '../constants/ActionTypes'

export function userLogin(email, password) {
    return {
        type: USER_LOGIN,
        email: email,
        password: password,
    };
}

export function userLogout() {
    return {
        type: USER_LOGOUT
    };
}

im be pleasure if i to know how should i do,

4

1 Answer 1

0

Have a look at the package redux-persist. This contains a function persistStore and the PersistGate component. This will rehydrate the store after reloading the page. And you have to choose in wich browser store the data will be saved. You can decide between session storage (per tab) or locale storage (per domain)

Here is the example for session storage

import { PersistGate } from 'redux-persist/lib/integration/react'
import { persistStore } from 'redux-persist'
import { persistReducer } from 'redux-persist'
import storage from 'redux-persist/es/storage/session'

const persistConfig = {
    key: 'root',
    storage,
}

const persistedReducer = persistReducer(persistConfig, reducer)

const store = createStore(persistedReducer);
const persistor = persistStore(store)
const customHistory = createHashHistory();



ReactDOM.render(
  <Provider store = {store}>
        <PersistGate persistor={persistor}>
...
1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.