0
votes

I'm new in react-native I've been trying to fetch data from an API and then show them in a view. this is my code

FetchSignatures.js :

    const URL = 'http://localhost:8000';

    export default {
     async fetchSignatures() {
       try{
           let response = await fetch(URL+'/api/signatures');
           let responseJsonData = await response.json();
           return responseJsonData;
       }
       catch(e){
         console.log(e)
       }
     }
    }

Signatures.js :

    import React, { Component } from 'react';
    import { View, Text, StyleSheet  } from 'react-native';
    import ajax from '../services/FetchSignatures';
    import SignaturesList from '../components/SignaturesList';

    export class Signatures extends Component {
      state = {
        signatures: []
      }

      async componentDidMount() {
        const signatures = await ajax.fetchSignatures();
        this.setState({signatures});
      }
      render() {
        return (
        <View>
        {
          this.state.signatures.length > 0 ? <SignaturesList signatures= 
          {this.state.signatures}/> : <Text>No Guest</Text>
        }
        </View> 
        )
      }
    }

    export default Signatures;

It always return an erro that said "TypeError: Undefined is not an object (evaluating 'this.state.signatures.length').

this is my API's screen shoot :

enter image description here

Please Somebody Help me to Solve this.. Thank's in advance..

1
Before setting the state please log the response signatures and see if you are getting them. If you are not getting a valid response, signatures might be null or undefined. - bennygenel
how do I do that? i use consolelog but i dont know where I can see the log.. - Almaida Jody
For more info about debugging react-native apps please visit facebook.github.io/react-native/docs/debugging - bennygenel

1 Answers

-1
votes

When you are rendering this.state.signatures.length, signatures is not created as a state at that time because it take some time to fetch data from API. This is the reason you are getting undefined error. So, just create a conditional rendering.

Try below code.

render() {
        if(this.state.signatures){
          return(
            this.state.signatures.length > 0 ? <SignaturesList signatures= 
            {this.state.signatures}/> : <Text>No Guest</Text>

          );
        }
  }