Baba
Baba

Reputation: 2209

Use data passed to a component in the componentdidmount method

I have a component called PrivateDataSingle below. I am able to pass customer data to this component from anywhere I am

    <PrivateDataSingle customer={this.state.customer}/> :

I want to use the customerId contained in my customer data in the method componentDidMount. This will be used as part of an api to return data.

It seems as if my customer information does not exist in componentDidMount method. How can I make this available ?

It exists in the other sections of the component though.

    class PrivateDataSingle extends PureComponent {
         state = {
           invoices:[]
         }

         componentDidMount() {
          const getCustomerId = customer.customerId; ??
          AXIOS_AUTHED.get(`${API}/customers/${getCustomerId}/invoices`)
            .then(res => {
              const invoices= res.data;
              this.setState({ invoices });
            })  
        }

      render() {
        return (
          <h2>Hello world</h2>
        );
      }
    }

    export default PrivateDataSingle;

Upvotes: 2

Views: 31

Answers (1)

0xc14m1z
0xc14m1z

Reputation: 3725

When you render your component this way:

<PrivateDataSingle customer={this.state.customer} />

You are passing customer as a prop.

In your componentDidMount you can retrieve it this way:

const getCustomerId = this.props.customer.customerId;

Upvotes: 3

Related Questions