Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need to Execute Function before render() in ReactJS

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.

like image 929
Matt Avatar asked Dec 18 '22 21:12

Matt


1 Answers

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

like image 128
Anil Singh Avatar answered Dec 28 '22 10:12

Anil Singh