#StackBounty: #javascript #reactjs Data not refreshing after login to homepage in reactjs

Bounty: 50

I’m saving userdata to localStorage in login component and then redirecting to the homepage. In homepage username is not updating on first visit. I have to reload the page. Then data binds to page after refresh. Please help how can I show data on first visit?

below is my homepage code

import React, { Component } from 'react';
import { Link } from 'react-router-dom';

export default class Header extends Component {
  constructor(props) {
    super(props);
    this.state = {
      isLogin: false,
      isLogout: false,
      user: ""
    };
  }

  componentDidMount() {
    const userData = localStorage.getItem("userData");
    const user = JSON.parse(userData);
    this.setState({ user: user });
    if (userData) {
      this.setState({ isLogin: true });
    }
    console.log(userData);
    console.log(user);
  }

  logout = e => {
    e.preventDefault();
    localStorage.clear();
    this.setState({ isLogout: true });
  };

  render() {
    if (this.state.isLogin === false || this.state.isLogout === true) {
      return (
        <header
          id="kr-header"
          className="kr-header cd-auto-hide-header kr-haslayout"
        >
          
company logo here

Below is login-register component code

import React, {Component} from 'react';
import { Link,Redirect ,withRouter } from 'react-router-dom';
import PropTypes from "prop-types";
import Otp from './otp';
import axios from '../api';

export default class LoginRegister extends Component {
    static contextTypes = {
        router: PropTypes.object
      }
    constructor(props,context){
        super(props,context);
        this.state = {
            fname:'',
            lname:'',
            emailaddress:'',
            password:'',
            mobile:'',
            user:'',
            login_pass:'',
            isLogin:false
        }
        this.regi_data = this.regi_data.bind(this);
        this.login_data = this.login_data.bind(this);
        // this.otpModalRef = React.createRef();
    }

    regi_data(e){
        this.setState({[e.target.name] : e.target.value}
        );
    }
    login_data(e){
        this.setState({[e.target.name] : e.target.value})
    }

    // otpModalRef = ({onOpenModal}) => {
    //    this.showModal = onOpenModal;
    // }

    componentDidMount(){
        if (localStorage.getItem('userData')) {
            this.context.router.history.push({
                        pathname:'/',

                    });
        }
    }




    login = (e) => {
        e.preventDefault();
         axios.post('/api/signin', { 
                        user:this.state.user,
                        password:this.state.login_pass,
                    })
          .then(res => {
                //console.log(res);
                localStorage.setItem('userData', JSON.stringify(res.data));
                this.context.router.history.push({
                        pathname:'/',

                    });
//                  window.location.reload();
                    this.setState({isLogin: true});
          })
          .catch(function (error) {
            console.log(error.message);
          })
    }

    register = (e) => {
        e.preventDefault(); 
        axios.post('/api/user/add', { 
                        firstname: this.state.fname,
                        lastname:this.state.lname,
                        email:this.state.emailaddress,
                        password:this.state.password,
                        mobile:this.state.mobile 
                    },              
                )
          .then(res => {
                console.log(res);
                // this.showModal();
                 this.context.router.history.push({
                        pathname:'/otp_validate',
                    });            
          }).catch(function(error){
            alert(error.message)
          })
    }


Get this bounty!!!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.