how to deal with returning no data in the render method?

178 views Asked by At

I am calling a const in the render() which does not return anything due to not finding data in the database and I don't know how to deal with it so that whenever there is nothing to return, just dont display anything. It displays an error saying: "Invariant violation : Component(...): Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null."

render() {
    const food_menu = this.restaurantMenu(1, 'Menu');

    return (
        <View style={{ flex: 1 }}>
            <ScrollView style={style_2.scrollview} scrollEventThrottle={200} directionalLockEnabled=true}>

                {food_menu}

            </ScrollView>
        </View >
    );
}

Edit(return from food_menu):

    $$typeof: Symbol(react.element)
type: {$$typeof: Symbol(react.forward_ref), displayName: "View", render: ƒ}
key: null
ref: null
props: {style: {…}, children: Array(3)}
_owner: FiberNode {tag: 1, key: null, stateNode: selected_restaurant, elementType: ƒ, type: ƒ, …}
_store: {validated: false}
_self: null
_source: {fileName: "C:\vvv\ddd\selected_restaurant.js", lineNumber: 428}
__proto__: Object
2

There are 2 answers

0
TrueXPixels On

You can look into conditional rendering.

More information: https://reactjs.org/docs/conditional-rendering.html

Example:

render() {
    const food_menu = this.restaurantMenu(1, 'Menu');

    return (
        <>
            {food_menu && <View style={{ flex: 1 }}>
                <ScrollView style={style_2.scrollview} scrollEventThrottle={200} directionalLockEnabled=true}>

                    {food_menu}

                </ScrollView>
            </View >}
        </>
    );
}
2
parichay28 On

Assuming this.restaurantMenu() returns a Valid React component this should get you going.

render() {
    const food_menu = this.restaurantMenu(1, 'Menu');

    return (
        <View style={{ flex: 1 }}>
            <ScrollView style={style_2.scrollview} scrollEventThrottle={200} directionalLockEnabled=true}>

                {food_menu ? food_menu || null}

            </ScrollView>
        </View >
    );
}

Obviously there are better ways to go about this problem. One would be to set state inside restaurantMenu indicating a successful loading of restaurant menu and then rendering accordingly. In that case, the conditional rendering would change to:

{menuLoaded ? food_menu : null }