Syed Aon Ali Naqvi
Syed Aon Ali Naqvi

Reputation: 1

error Objects are not valid as react child in react native, when i call async function in render method

i am calling this function in Render method in React Native code, but it shows the error, objects are not valid as react child

display = async () => {
    a="Hellow";
    return a;
}

render() {
    return (
      <View>
        <Text>{await this.display()}</Text>
      </View>
    );
}

Upvotes: 0

Views: 124

Answers (2)

jvgaeta
jvgaeta

Reputation: 103

You don't need this.display to be async, so this could be written as

display = () => {
    a = "Hellow";
    return a;
}

render() {
    const display = this.display();
    return (
      <View>
        <Text>{display}</Text>
      </View>
    );
}

Furthermore, if you are trying to do something asynchronously to change what is rendered, it should be done in the componentDidMount method. This is where you would set the state for the component.

async componentDidMount {
    ...
    const display = await fetchData(url);
    this.setState({ display });
}

render() {
    return (
      <View>
        <Text>{this.state.display}</Text>
      </View>
    );
}

Upvotes: 1

M. Alex
M. Alex

Reputation: 713

A better way to do this would be to store the text you want to display in state in the componentDidMount function and then render it like this rather than running a function in the render method:

componentDidMount = () => {
    a = "hellow"
    this.setState({ text: a })
}

render () {
    return (
        <Text>{this.state.text}</Text>
    )
}

Upvotes: 0

Related Questions