About bind() in Social network for pets

In this project, guide doesn’t mention about bind() for a method that change a statement. I thought every methods should be bonded to ‘this’. In this project, loadUserData().

I have question what kinda situation we don’t need bind to this for a method even the method change statement?

project URL
https://www.codecademy.com/courses/react-101/projects/react-lifecycle-methods-social-network-for-pets

import React from 'react';
import { fetchUserData, cancelFetch } from './dataFetcher';
import { Userlist } from './Userlist';

export class Profile extends React.Component {
  constructor(props){
    super(props);
    this.state = { userData: null}
  }

  loadUserData(){
    this.setState({ userData: null})
    this.fetchID = fetchUserData(this.props.username, (userData) => {
      this.setState({ userData});
    })
  }

  componentDidMount(){
    this.loadUserData()
  }

  componentWillUnmount(){
    cancelFetch(this.fetchID)
  }

  componentDidUpdate(prevProps){
    if(this.props.username !== prevProps.username){
      cancelFetch(this.fetchID)
      this.loadUserData()
    }
  }

  render() {
    const isLoading = this.state.userData === null ? true : false;

    let className = 'Profile';
    if (isLoading) {
      className += ' loading';
    }

    const  name = isLoading ? "Loading..." : this.state.userData.name;
    

    let bio;
    if(isLoading){
      bio = 'Loading...'
    }else{
      bio = this.state.userData.bio;
    }

    let friends;
    if(isLoading){
      friends = [];
    }else{
      friends = this.state.userData.friends;
    }

    return (
      <div className={className}>
        <div className="profile-picture">
        {!isLoading && <img src={this.state.userData.profilePictureUrl} alt="" />
}
        </div>
        <div className="profile-body">
          <h2>{name}</h2>
          <h3>@{this.props.username}</h3>
          <p>{bio}</p>
          <h3>My friends</h3>
          <Userlist usernames={friends} onChoose={this.props.onChoose} />
        </div>
      </div>
    );
  }
}

This page has better answers than I could give: https://reactjs.org/docs/faq-functions.html

See specifically the question: Why is binding necessary at all?

2 Likes

That is what I want to know! Thank you javaace96747 again.!