hanan
hanan

Reputation: 632

assign json data returned from the server to state variable and then iterate over it

Here I wanted to fetch data from the server and show it to the user. I am implementing on react-native. the server returns a bunch of Json data. later than I store returned json data into a state. when displaying the data I only wanted to show the user last three transactions if more transactions existed. but I am facing an error TypeError: undefined is not an object (evaluating 'n.transactions[t].amount'). below is the code I tried:


const MyHomeScr = () => {

const [rspnsData, setRspnsData] = useState('');


 const REQ = (m, p) => {
    fetch(url, {
      method: GET, // *GET, POST, PUT, DELETE, etc.
      headers: {
        ChannelDetails: 'Unknown',
        Accept: 'application/json ; charset=utf-8',
        'Cache-Control': 'no-cache',
        'Accept-Encoding': 'gzip, deflate',
      }
    })
      .then(response => response.json())
      .then(data => {

        'accounts' in data
          ? setRspnsData(data['accounts']) 
          : setRspnsData(data['message']);
        }
        
      })
      .catch(error => {
        console.Error('Error:', error);
      });
  };

 var hData = [];


   
    for (let i = 0; i < 3; i++) {
    hData.push(
      <FlatList
        style={styles.flatStyleData}
        data={rspnsData}
        renderItem={({item}) => (
          <View>
            <Text style={styles.flatListDataText}>
              {'\t\t\t\t\t\t\t'}Amount:{'\t\t'}
              {item.transactions[i].amount}
            </Text>
            <Text style={styles.flatListDataText}>
              {'\t\t\t\t\t\t\t'}to AccNo:{'\t\t'}
              {item.transactions[i].toAccount}
            </Text>
            <Text style={styles.flatListDataText}>
              {'\t\t\t\t\t\t\t'}Date:{'\t\t'}
              {item.transactions[i].tranDate
                .toString()
                .substring(0, 8)
                .replace(/\d{2}(?=.)/g, '$& ')
                .slice(0, -3) + ''}
            </Text>
 
          </View>
        )}
        listKey={(item, index) => 'D' + index.toString()}
        refreshing={true}
      />,
    );
  
  }

return (

<View>
{rspnsData !== '' ? (
        <View>
          <FlatList
            style={styles.flatStyle}
            data={rspnsData}
            renderItem={({item}) =>
              item.accountNumber === undefined ? (
                <View>
                  <Text style={styles.flatListText}>{rspnsData}</Text>
                </View>
              ) : (
                <View>
                  <Animatable.View animation="fadeInLeft" duration={500}>
                    <Text style={styles.flatListText}>
                      Account No: {item.accountNumber}
                    </Text>
                    <Text style={styles.flatListText}>
                      Name:{'\t\t\t\t'} {item.name}
                    </Text>
                    <Text style={styles.flatListText}>
                      Type:{'\t\t\t\t\t\t\t\t'} {item.type}
                    </Text>
                    <Text style={styles.flatListText}>
                      Balance:{'\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t'}{' '}
                      {item.availableBalance}
                    </Text>
                    {/* <Text>{'\n'}</Text> */}
                    <Text
                      style={{
                        fontFamily: 'fantasy',
                        fontWeight: 'bold',
                        alignSelf: 'center',
                        marginTop: 7,
                      }}>
                      last 3 trans:
                      {'\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t'}
                    </Text>
                    {hData}
                  </Animatable.View>
                </View>
              )
            }
            listKey={(item, index) => index.toString()}
            refreshing={true}
          />
        </View>
      ) : null}
    </View>

)


}



the problem exists in the for loop , trying to iterate over json data, there will be undefined error if returned json data contains less than 3 transactions. I have tried to solve like below code: typeof (item.transactions[i].amount) !== 'undefined' ? ... :null but nothing avail. my intention is that the user should see 3 transactions if there are more transactions.

How can I solve this?

Upvotes: 1

Views: 49

Answers (2)

Your hData loop is wrong instead use this FlatList. So just replace {hData} for this Flatlist


     <FlatList
        style={styles.flatStyleData}
        data={rspnsData}
        renderItem={({item}) => {
          const data = item.transactions.length > 3? item.transactions.slice(-3) : item.transactions;
          return data.map((transaction) => (<View>
            <Text style={styles.flatListDataText}>
              {'\t\t\t\t\t\t\t'}Amount:{'\t\t'}
              {transaction.amount}
            </Text>
            <Text style={styles.flatListDataText}>
              {'\t\t\t\t\t\t\t'}to AccNo:{'\t\t'}
              {transaction.toAccount}
            </Text>
            <Text style={styles.flatListDataText}>
              {'\t\t\t\t\t\t\t'}Date:{'\t\t'}
              {transaction.tranDate
                .toString()
                .substring(0, 8)
                .replace(/\d{2}(?=.)/g, '$& ')
                .slice(0, -3) + ''}
            </Text>
 
          </View>));
        }}
        listKey={(item, index) => 'D' + index.toString()}
        refreshing={true}
      />

Upvotes: 2

Guruparan Giritharan
Guruparan Giritharan

Reputation: 16354

You can use the slice method of the array with a negative number which will chose the last three items like below

const data = item.transactions.slice(-3);

here data would have the last three items which you can use in your flatlist or map.

Upvotes: 1

Related Questions