Maifee Ul Asad
Maifee Ul Asad

Reputation: 4607

reactjs check for data update

I have GUser class, in my project to store data from GitHub-api and process them :

import axios from "axios";
export default class GUser {
    constructor(userName) {
        this.userName=userName;
        this.getUserData(this,userName);
    }
    getUserData(that, userName) {
        if(that.data===undefined)
        {
            axios.get('https://api.github.com/users/'.concat(userName))
                .then(function (response) {
                    that.data = response.data;
                    console.log(that);
                    return that.data;
                })
                .catch(function (error) {
                    console.log(userName+ " got error " +error);
                });
        }
        else{return that.data;}
    }
}

I'm trying to sync pages, so in my TestRender I wrote :

import React from 'react';
import GUser from "../model/GUser";
class TestRender extends React.Component{
    userName='maifeeulasad';
    user=new GUser(this.userName);
    componentWillMount() {
        try {
            console.log(this.user.getUserData());
        }
        catch (e) {console.log(e);}
    }
    componentDidMount() {
        try {
            console.log(this.user.getUserData());
        }
        catch (e) {console.log(e);}
    }
    render() {
        return(
            <div>
            </div>
        );
    }
}
export default TestRender;

My target is to console log the data, as soon as it gets received.

How can I do this ?

Previously I used componentWillMount only, when I loaded data from the same script. It's currently giving me TypeError: Cannot read property 'data' of undefined, maybe because of I haven't specified data as state in GUser, but it gets created through time right ?

Upvotes: 0

Views: 890

Answers (1)

macabeus
macabeus

Reputation: 4582

Looks like you are using object's attribute to store the state's component, that isn't good, because React will not to re-render the component when these values are updated.
Every instance of TestRender should have the same value of userName and user as attribute? These values are always the same? If not, use useState for that.

Also, componentDidMount and componentWillMount will be called only when the component is being mounted, and at this moment you didn't finished the fetch, so you don't have yet the value to print. It's an async problem.

To handle with async challenges, I recommend to use useEffect.

Upvotes: 1

Related Questions