1

I have 2 components, the first component has a function that calls after the async function of the second component, what I want to do is something like vue's this.$emit() function that calls a listener from that component anytime, how can I do that in react?

This is my first component

import React, { Component } from 'react';
import SecondComponent from '../Path/to/second/component'

class MainMenu extends Component {
    callThis (data) {
        console.log(data)
    }

    render () {
        return <SecondComponent onDataReceived = {this.callThis} />
    }
}

export default FirstComponent

And this is my SecondComponent

import React, { Component } from 'react';

class SecondComponent extends Component {
    async asyncFunction () {
        const data = await getDataFromApi()
        // call the function from first component here...
    }

    render () {
        return <button onClick={() => this.asyncFuncion} />
    }
}

export default FirstComponent
1
  • Second Component's onClick is not executing asyncFunction;either write onClick={this.asyncFunction} or onClick={()=>this.asyncFunction()} And inside your asyncFunction call this.props.onDataReceived(); Commented Aug 26, 2019 at 10:49

3 Answers 3

1

Your second component must invoke asyncFuncion, and then inside asyncFuncion you can call the callThis function from the props

class SecondComponent extends Component {
    async asyncFunction () {
        const data = await getDataFromApi()
        this.props.onDataReceived(data)
    }

    render () {
        return <button onClick={() => this.asyncFuncion()} />
    }
}

and do not forget to bind that callThis as well, or just use fat arrow function:

class MainMenu extends Component {
    callThis = (data) => {
        console.log(data)
    }
Sign up to request clarification or add additional context in comments.

Comments

1

On your first component, you are sending a props to your second components. Here is the documentation : https://reactjs.org/docs/components-and-props.html

To access onDataReceived in your second component you could write :

async asyncFunction () {
        const data = await getDataFromApi()
        this.props.onDataReceived(data);
    }

Comments

1

this is how you can receive data/use methods from parent passed props:

async asyncFunction () {
    const data = await getDataFromApi()
    // call the function from first component here...
    this.props.onDataReceived(data);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.