J. Sel
J. Sel

Reputation: 23

How can I set value to componentDidMount from another function in React?

I wanted set value to componentDidMount in PeopleItem file from outside function and get return value. Is this possible? I am getting error when I executing the program. I started React newly. Can you give me an idea please? Thank you in advance..

import React from "react";
import axios from "axios";

class PeopleItem extends React.Component {
  async componentDidMount(val) {
    const response = await axios.get(val);
    return response.data;
  }

  _renderObject() {
    const { data } = this.props;
    return Object.entries(data.films).map(([key, value], i) => {
      return <div key={key}>{this.componentDidMount({ value })}</div>;
    });
  }

  render() {
    const { data } = this.props;
    return (
      <div>
        Star Name: {data.name} <br />
        Films:
        {this._renderObject()}
      </div>
    );
  }
}

export default PeopleItem;

Upvotes: 1

Views: 3500

Answers (2)

Astrit Spanca
Astrit Spanca

Reputation: 724

Note: This is not an explicit answer to you questions as you need to understand basic concepts of Reactjs.

A Reactjs Lifecycle Hook is a 'function' which manipulates the state and this way triggers changes into the dom and only.

All the variables and functions created inside a lifecycle hook have a short life span and are finished whenever lifecycle hook finishes execution.

In your case you have to set all those properties that you intend to access, inside State Object and change them through functions and lifecycle hooks.

It doesn't matter if the code is asynchronous or not, as long as it is inside Lifecycle hook it will execute, change the state, and re render component with the new changes.

Below you have an example:

class sto extends Component {
    state = {
        time: 0
    }

    componentDidMount(){
        //you have no access here from outside
        // when the component mounts it gets the actual date and replaces time property with the actual date
        let date = new Date();
        //async function
        setTimeout(() => {
          this.setState({ date: date });
        }, 5000);
    }

    resetDate = () => {
        // when click event is fired
        // you reset the time property inside state and the change reflects in your component
        this.setState({ time: 0 });
    }

    render() {
        return (
            <div>
                {/* show date */}
                { this.state.date }
                <button onClick = { this.resetDate }>Change Date</button>
            </div>
        );
    }
}

Upvotes: 0

Shubham Verma
Shubham Verma

Reputation: 5054

You need to study about setState in react. React work on states. In your case. It should be like this :

import React from 'react';
import axios from 'axios';

    class PeopleItem extends React.Component{
        state ={
            data:[]
        }
        async componentDidMount() {
            const response = await axios.get(val);
            this.setState({data:response}) //now you can consume it this data in using states
        }

        _renderObject(){
            const {data} = this.props;
            return Object.entries(data.films).map(([key, value], i) => {
                return (
                    <div key={key}>
                        {this.state.data}
                    </div>
                )
            })
        }

        render(){
            const {data} = this.props;
            return (
                    <div>
                        Star Name: {data.name} <br/>
                        Films: 
                        {this._renderObject()}
                    </div>
            );
        }
    }

    export default PeopleItem;

Please explain more about your problem. I just gave you overview.

From my understanding it should be like this you need to pass value to child component where it fetches data and render it into component :

class FetchData extends React.Component {
       async componentDidMount(){
           const response = await axios.get(this.props.val);
           this.setState({ data: response }) 
       }
       render(){
           return(
               <div>
                   Star Name: {data.name} <br />
                   Films:
                        {this.state.data}
               </div>
           )
       }
   }
    class PeopleItem extends React.Component{
        state ={
            data:[]
        }
        async componentDidMount(val) {
             //now you can consume it this data in using states
        }

        _renderObject(){
            const {data} = this.props;
            return Object.entries(data.films).map(([key, value], i) => {
                return (
                    <div key={key}>
                        <FetchData val={val}/>
                    </div>
                )
            })
        }
        fetchData(val){
            const response = await axios.get(val);
            this.setState({ data: response })
        }

        render(){
            return (
                    <div>         
                        {this._renderObject()}
                    </div>
            );
        }
    }

    export default PeopleItem;

Upvotes: 3

Related Questions