Click here to Skip to main content
15,881,967 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
i'm trying to get this xml data from sql database using fetch and then parsing it using xml2js package to a list called meterData after that i want to insert the xml data to an react native element ListItem.Accordion so far this is my code, the accordion appears but with a blank title and text and content with this message thrown in the console
Quote:
Unhandled promise rejection: TypeError: undefined is not an object (evaluating 'result['counter']['serviceNumber']')


What I have tried:

function getReadingOrder(Emp_Number,{navigation}){
  let meterDataList = React.useState({});
  fetch('http://server.com/gecol/partner/api.php?emp_number='+`${Emp_Number}`, {
  method: 'POST',
  headers: {
    Accept: 'text/plain',
    'Content-Type': 'text/plain'
  }
})
  .then((response) => response.text())
  .then((data) => { var xml2js = require('xml2js');

            var parser = new xml2js.Parser();
            parser.parseString(data, function(err,result){
            //Extract the value from the data element
            const meterData = {
              servicePoint:result['counter']['serviceNumber'],
              counternumber:result['counter']['counternumber'],
              consumer:result['counter']['consumername'],
              consumpationtype:result['counter']['consumpationtype'],
              currentread:result['counter']['currentread'],
              currentdate:result['counter']['currentdate'],
              lastread:result['counter']['lastread'],
              lastdate:result['counter']['lastdate'],
              consumpation:result['counter']['consumpation'],
              phonenumber:result['counter']['phonenumber'],
            }
            meterDataList.push(meterData);
            // getRounds(meterData);
      })
    })
    const [expanded, setExpanded] = React.useState(true);
    return (  
      
      <SafeAreaProvider >
        <View style={ReaderHome.Accordion}>
          {meterDataList.map((meter, i) => (
          <ListItem.Accordion 
            content={
              <>
              <Avatar size={64} icon={{ name: 'home', type: 'AntDesign' }} containerStyle={{ backgroundColor: '#1f95c0' }}/>
              <ListItem.Content>
                <ListItem.Title style={{left:10}}><Text style={ReaderHome.ConsumerName}>{meter.consumer}</Text></ListItem.Title>
                <ListItem.Subtitle style={{left:10}}><Text style={ReaderHome.ServiceNumber}>{meter.servicePoint}</Text></ListItem.Subtitle>
                </ListItem.Content>
              </>
            }
            isExpanded={expanded}
            onPress={() => {
              setExpanded(!expanded);
            }}
              >
              <ListItem key={i} onPress={alert(meter.lastdate)} bottomDivider>
                <Avatar title={''} source={''} />
                  <ListItem.Content>
                    <ListItem.Title>{meter.currentread}</ListItem.Title>
                    <ListItem.Subtitle>{meter.lastread}</ListItem.Subtitle>
                  </ListItem.Content>
                  <ListItem.Chevron />
              </ListItem>
          </ListItem.Accordion>))}
        </View>
      </SafeAreaProvider>);
      
  }
Posted
Updated 29-Nov-22 11:51am
v2

1 solution

Two things in your exception:
Quote:
Unhandled promise rejection
This can be resolved by wrapping your code with a try...catch block that will help you capture the exception and check the details. When working with exceptions, it is always recommended to use the exception handler because implicit exception handling is discouraged in JavaScript.
Quote:
TypeError: undefined is not an object (evaluating 'result['counter']['serviceNumber']')
For this one, I think the problem is with the counter argument. One of the reasons this is happening is because your result object does not contain a counter—thus, reading the serviceNumber is not possible because the field counter is undefined.

Tip: When working with an API that does not guarantee the data structure (for example, often provides null values or ignores providing the unavailable data), you must always use if...else to verify that the objects are not null or undefined.
 
Share this answer
 
Comments
Richard Deeming 30-Nov-22 4:59am    
"you must always use if...else to verify that the objects are not null or undefined"
Or use Optional chaining (?.)[^]:
result.counter?.serviceNumber
MohammedZr 30-Nov-22 5:25am    
As you can see in the code there is
onPress={alert(meter.lastdate)}
When clicking on the item i get undefined
Richard Deeming 30-Nov-22 5:30am    
And? That just means the counter.lastdate property is undefined.

You need to check your data source to find out why. Nobody else can do that for you.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900