skip to Main Content

console inside MyComponent print value for the first time but value dose not show on view.

import React, { useEffect, useState } from "react";

const withLoading = (WrappedComponent) => {

    class WithLoading extends React.Component {
        constructor(props) {
            super(props)
            this.state = { loading: true };
        }

        componentDidMount() {
            setTimeout(() => {
                console.log("setTimeout")
                this.state = { loading: false };
            }, 5000)
        }

        render() {
            console.log("render", this.state.loading)
            return <WrappedComponent {...this.props} loading={this.state.loading} />;
        }

    }

    WithLoading.displayName = `withLoading(${WrappedComponent.displayName || WrappedComponent.name})`;

    return WithLoading;

}


function MyComponent({ loading }) {
    console.log("MyComponent loading", loading)
    return (<p>is loading:{loading}</p>)
}


const hoc = withLoading(MyComponent);

export default hoc

2

Answers


  1. Chosen as BEST ANSWER

    Found the problem:

    Problem 1: state not changed correctly

     this.setState({ loading: false });
    

    Problem 2: Inside My component loading prop must use in correct way.

            {loading ? <p>Loading...</p> : <p>Hello, world!</p>}
    
    

  2. Change this.state = { loading: false } to this.setState({ loading: false }):

    import React, { useEffect, useState } from "react";
    
    const withLoading = (WrappedComponent) => {
    
        class WithLoading extends React.Component {
            constructor(props) {
                super(props)
                this.state = { loading: true };
            }
    
            componentDidMount() {
                setTimeout(() => {
                    console.log("setTimeout")
                    this.setState({ loading: false });
                }, 5000)
            }
    
            render() {
                console.log("render", this.state.loading)
                return <WrappedComponent {...this.props} loading={this.state.loading} />;
            }
    
        }
    
        WithLoading.displayName = `withLoading(${WrappedComponent.displayName || WrappedComponent.name})`;
    
        return WithLoading;
    
    }
    
    
    function MyComponent({ loading }) {
        console.log("MyComponent loading", loading)
        return (<p>is loading:{loading}</p>)
    }
    
    
    const hoc = withLoading(MyComponent);
    
    export default hoc
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search