I've created a login system with React which stores a session when the user logs in. When the page is reloaded, I have added a function which should check if the session exists and then either setState() to true or to false.
As I'm new to React, I'm not sure how to execute this function. Please see my code below for App.js:
import React from 'react';
import './css/App.css';
import LoginForm from "./LoginForm";
import Dashboard from "./Dashboard";
class App extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            renderLoginForm: true
        };
        this.handleLoginFormMount = this.handleLoginFormMount.bind(this);
    }
    handleLoginFormMount() {
        this.setState({
            renderLoginForm: false
        });
    }
    // Check session function.
    checkSession() {
        fetch('/check-session', {
            credentials: 'include'
        })
        .then((response) => {
            return response.json();
        })
        .then((sessionResult) => {
            if (sessionResult.username) {
                console.log('false');
                this.setState({
                    renderLoginForm: false
                });
            } else {
                console.log('true');
                this.setState({
                    renderLoginForm: true
                });
            }
        })
        .catch((error) => {
            console.log('Error: ', error);
        });
    }
    render() {
        checkSession();
        return (
            <div className="App">
                {this.state.renderLoginForm ? <LoginForm mountLoginForm={this.handleLoginFormMount} /> : null}
                {this.state.renderLoginForm ? null : <Dashboard />}
            </div>
        );
    }
}
export default App;
Having checkSession() in this position outputs the following in the console when loading the page:
Line 50:  'checkSession' is not defined  no-undef
If I put the function outside of the class App extends React.Component {}, then it tells me that I cannot set the state of undefined.
Functional Component: In my case I wanted my code to run before component renders on the screen. useLayoutEffect is a hook provided by React for this exact purpose.
import React, { useLayoutEffect } from "react";
...
const App = () => {
   
    useLayoutEffect(() => {
        //check local token or something
    }, []);
}
Read More: https://reactjs.org/docs/hooks-reference.html#uselayouteffect
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With