briankwlin
briankwlin

Reputation: 43

Modals in React Native resulting in infinite while loop

I'm just wondering why the code snippet below results in an infinite while loop while causing my emulator to hang with the error "Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate".

import React, { Component } from 'react';
import * as firebase from 'firebase';
import { ActivityIndicator, ListView, Modal, Text, View, Button, StyleSheet } from 'react-native';

export default class GroceryList extends Component {
    constructor(props) {
        super(props);
        this.state = {
            modalVisible: false,
        };
    }

    render() {
        return(
            <View style={styles.container}>
                <Text>hi</Text>
                <Modal
                    visible = {this.setState({modalVisible: false})}
                    animationType={'slide'}
                    onRequestClose={this.setState({modalVisible: false})}
                >
                    <View style={styles.modalContainer}>
                        <View style={styles.innerContainer}>
                            <Text>This is content inside of modal component</Text>
                            <Button
                                onPress={this.setState({modalVisible: false})}
                                title="Add to cart"
                            />
                        </View>
                    </View>
                </Modal>
                <Button
                    onPress={this.setState({modalVisible: true})}
                    title="PURCHASE ITEM"
                    color="#841584"
                />
            </View>
        );
    }
}

const styles = StyleSheet.create({
    container:{
        flex: 1,
        justifyContent: 'center',
        marginTop: 50,
    },
    buttonContainer: {
        margin: 20,
    },
    modalContainer: {
        flex: 1,
        justifyContent: 'center',
        backgroundColor: 'grey',
        height: 20,
    },
    innerContainer: {
        alignItems: 'center',
    },
})

Upvotes: 1

Views: 1020

Answers (2)

Marcos Dem&#233;trio
Marcos Dem&#233;trio

Reputation: 1417

Can you try this change in your button?

<Button
  onPress={() => this.setState({modalVisible: true})}
  ...
/>

You can't use this.setState() directly in your render method.

Upvotes: 1

asubanovsky
asubanovsky

Reputation: 1748

Should be:

<Modal
                visible = {this.state.modalVisible}
                animationType={'slide'}
                onRequestClose={this.setState({modalVisible: false})}
            >

Upvotes: 0

Related Questions