Gario3
Gario3

Reputation: 137

Problem with conditional rendering on React-native and AXIOS

I have a big problem in react native, I have this:

getreportbycode = async() => {
        this.setState({show : false})
        if(this.state.finder !== ''){
            const token = await AsyncStorage.getItem('petra-token');
            this.setState({ jwt: token, sendform: true });
            axios.post('https://petrapi.herokuapp.com/emergence/find', {
                report_id : this.state.finder
        }, {headers: {
                Authorization: `Bearer ${this.state.jwt}`
        }
            }).then(response => {
                this.setState({report: response.data.data, sendform:false})
                console.log(this.state.report)
                this.setState({mostrar : true})

        }).catch(error => {
            this.setState({finder:'', sendform:false})
            console.log(error)
        })
        }
    }

and this :

report(report){
        if(this.state.show == true){
            return(
                <Card>
                    <CardItem>
                            <Left>
                            { report.alert.image == null
                            ?
                            <Thumbnail source={{uri:
                            'https://cdn2.iconfinder.com/data/icons/user-icon-2-1/100/user_5-15-512.png' }}
                            
                                style={{height: 50, width: 50}}/>
                            :
                            <Thumbnail source={{uri: report.alert.image}}
                            style={{height: 50, width: 50}}/>
                            }
                        </Left>
                        <Body>
                            <Text>
                                Creador: {report.user.name}
                            </Text>
                            {this.proccesbar(report.status)}
                        </Body>
                    </CardItem>
                    </Card>
)}

The problem is only when i tried catch "error" i have this error message :

only when i tried catch error

Is there any way to do this correctly?

Upvotes: 0

Views: 139

Answers (1)

Beatriz Rezener
Beatriz Rezener

Reputation: 91

Seems like you are trying to obtain an image value of an undefined object. So, instead of only check if report.alert.image is null, you could also verify if report and alert objects has value, like:

    (...)
    {
      (report?.alert?.image) ?
         <Thumbnail source={{uri: report.alert.image}} style={{height: 50, width: 50}}/>
      :
         <Thumbnail source={{uri: 'https://cdn2.iconfinder.com/data/icons/user-icon-2-1/100/user_5-15-512.png' }} style={{height: 50, width: 50}}/>
    }
    (...)

Upvotes: 2

Related Questions