0

I have an array of Data objects that contain another array of Attendance and I want to access the all attendance attributes. I need to be able to insert data into checkIn, checkOut and total hours that belong to the nested array called attendance. I unable to fetch these type of data from HTTP request please suggest and check my code. And I also wanted to know that how can we fetch multiple array data from JSON API?

"data": [
    {
        "id": 40,
        "addEmployee": {
            "firstName": "Divyanshu"
        },
        "attendances": [
            {
                "id": 615,
                "checkIn": null,
                "checkOut": "2020-04-17T04:54:15.000Z",
                "totalHours": "NaN:NaN",
                "date": "2020-04-17",
                "status": "present",
                "createdAt": "2020-04-16T13:57:30.000Z",
                "updatedAt": "2020-04-17T04:54:15.000Z",
                "userId": 40
            }
        ]
    },
    {
        "id": 21,
        "addEmployee": {
            "firstName": "Narayan"
        },
        "attendances": [
            {
                "id": 617,
                "checkIn": "2020-04-17T05:20:45.000Z",
                "checkOut": "2020-04-17T05:21:22.000Z",
                "totalHours": "0:0",
                "date": "2020-04-17",
                "status": "present",
                "createdAt": "2020-04-17T05:20:45.000Z",
                "updatedAt": "2020-04-17T05:21:22.000Z",
                "userId": 21
            },
        ]
    },
    {
        "id": 20,
        "addEmployee": {
            "firstName": "Himanshu"
        },
        "attendances": []
    },
    0'.v\zcfipzgzy
],
    "status": 1
 }

I am able to insert data to a normal array. But I don't know how to insert to a nested array and I unable to Access Attendance data from Above nested array data.

componentDidMount() {
    const url = 'http://104.197.28.169:3000/todayAttendanceList'
    fetch(url)
        .then(response => response.json())
        .then((responseJson) => {
            console.log("aagiyo", responseJson)
            this.setState({
                dataSource: responseJson,
                isLoading: false
            })
        })
        .catch(error => console.log(error))
}

<FlatList
    data={this.state.dataSource}
    renderItem={({ item }) =>
        <View style={styles.firstV1}>
            <View style={styles.heading}>
                <Text style={{ fontSize: 15 }}>{item.attendances.checkIn}</Text>
            </View>
            <View style={styles.heading}>
                <Text style={{ fontSize: 15, }}>{item.attendances.checkOut}</Text>
            </View>
            <View style={styles.heading}>
                <Text style={{ fontSize: 15 }}>{item.attendances.totalHours}</Text>
            </View>
        }
         ItemSeparatorComponent={this.renderSeperator}
       />

3 Answers 3

1

You can do something like this to display the attendances by using your API:

import React from 'react';
import {View, FlatList, Text} from 'react-native'; 

export default class App extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            data:[
                {
                    "id": 40,
                    "addEmployee": {
                        "firstName": "Divyanshu"
                    },
                    "attendances": [
                        {
                            "id": 615,
                            "checkIn": null,
                            "checkOut": "2020-04-17T04:54:15.000Z",
                            "totalHours": "NaN:NaN",
                            "date": "2020-04-17",
                            "status": "present",
                            "createdAt": "2020-04-16T13:57:30.000Z",
                            "updatedAt": "2020-04-17T04:54:15.000Z",
                            "userId": 40
                        }
                    ]
                },
                {
                    "id": 21,
                    "addEmployee": {
                        "firstName": "Narayan"
                    },
                    "attendances": [
                        {
                            "id": 617,
                            "checkIn": "2020-04-17T05:20:45.000Z",
                            "checkOut": "2020-04-17T05:21:22.000Z",
                            "totalHours": "0:0",
                            "date": "2020-04-17",
                            "status": "present",
                            "createdAt": "2020-04-17T05:20:45.000Z",
                            "updatedAt": "2020-04-17T05:21:22.000Z",
                            "userId": 21
                        },
                    ]
                },
                {
                    "id": 20,
                    "addEmployee": {
                        "firstName": "Himanshu"
                    },
                    "attendances": []
                },
            ],
         };
        }

    render() {
        return (
            <FlatList
            data={this.state.data}
            renderItem={({ item }) =>
            { 

                return(
                    <View style={{alignItems:"center",justifyContent:"center",marginTop:50}}>
            <Text style={{fontWeight:"bold",fontSize:18}}>Attendance of {item.addEmployee.firstName}</Text>
                    <View>
                        <Text style={{ fontSize: 15 }}><Text style={{fontWeight:"bold"}}>Check In:</Text>  {item.attendances.length >0 ? item.attendances[0].checkIn : null}</Text>
                    </View>
                    <View>
                        <Text style={{ fontSize: 15, }}><Text style={{fontWeight:"bold"}}>Check Out:</Text>{item.attendances.length >0 ? item.attendances[0].checkOut : null}</Text>
                    </View>
                    <View>
                        <Text style={{ fontSize: 15 }}><Text style={{fontWeight:"bold"}}>Total hours:</Text>{item.attendances.length >0 ? item.attendances[0].totalHours : null}</Text>
                    </View>
                    </View>
                )
            }
                }
               />
        );
      }
  }

enter image description here

Hope this helps!

Sign up to request clarification or add additional context in comments.

Comments

0

Use map function with spread syntax to insert data into checkIn, checkOut and totalHours values:

responseJson.map(item => ({...item, attendances: item.attendances.map(attendance => 
({...attendance, checkIn: 'your checkIn value', checkOut: 'your checkOut value', 
totalHours: 'totalHours value'}))}))

Comments

0

It's a bit unclear what you want to achieve. If you want to display all the list of attendances and the corresponding employees, use SectionList.

You can do something like:

change this statement:

this.setState({
                dataSource: responseJson,
                isLoading: false
            })

to:

const transformedData = responseJson.map(elem => ({
    key: elem.id,
    title: elem.addEmployee.firstName,
    data: elem.attendances
}))

this.setState({
    dataSource: responseJson,
    transformedDatasource: transformedData
    isLoading: false,
})

And replace your FlatList code with something like:

<SectionList
      sections={this.state.transformedDatasource}
      keyExtractor={(item, index) => item.id}
      renderItem={({ item }) =>
        <View style={styles.firstV1}>
            <View style={styles.heading}>
                <Text style={{ fontSize: 15 }}>{item.checkIn}</Text>
            </View>
            <View style={styles.heading}>
                <Text style={{ fontSize: 15, }}>{item.checkOut}</Text>
            </View>
            <View style={styles.heading}>
                <Text style={{ fontSize: 15 }}>{item.totalHours}</Text>
            </View>
        }}
      renderSectionHeader={({ section: { title } }) => (
        <Text>{title}</Text>
      )}
    />

2 Comments

I get a message "responseJson.map" is undefined during debug.
Ah, you can use some library like lodash to do help you out. In the terminal, do npm i lodash. At the top of file add import _ from 'lodash'; And in your code, use it like: ` const transformedData = _.map(responseJson, elem => ({ key: elem.id, title: elem.addEmployee.firstName, data: elem.attendances })) `

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.