0

I am working on a react and redux feature to get the users and their managers and I am getting a response from the API am calling. However, when I log the data on the console I get the following structure

[
  {id: 3, firstName: "benit", lastName: "havuga", email: "mujohn25@gmail.com", role: "requester", …},
  {id: 105, firstName: "Jordan", lastName: "Kayinamura", email: "jordankayinamura@gmail.com", role: "admin", …},
  {id: 1, firstName: "shema", lastName: "Eric", email: "ricshama@gmail.com", role: "requester", …}
]

while trying to access for example the id, I get '0' instead. now the question is, how can I access the actual data and why is the data returned like this?

Here is the codes to render the table component

import React, { Component } from 'react';
import { connect } from 'react-redux';
import { config } from 'dotenv';
import { makeStyles } from '@material-ui/core/styles';
import { withStyles } from '@material-ui/core/styles';
import { getUsersManagers, getUsersAction } from '../../actions/userManagementAction';
import Paper from '@material-ui/core/Paper';
import Table from '@material-ui/core/Table';
import TableBody from '@material-ui/core/TableBody';
import TableCell from '@material-ui/core/TableCell';
import TableContainer from '@material-ui/core/TableContainer';
import TableHead from '@material-ui/core/TableHead';
import TablePagination from '@material-ui/core/TablePagination';
import TableRow from '@material-ui/core/TableRow';
import TextField from '@material-ui/core/TextField';
import Autocomplete from '@material-ui/lab/Autocomplete';
import Button from '@material-ui/core/Button';



config();

const useStyles = theme => ({
  root: {
    width: '100%',
  },
  container: {
    maxHeight: 440,
  },
});

export class UserManagement extends Component {
  state = {
    page: 0,
    rowsPerPage: 5,
    isButtonDisabled: true
  }
  UNSAFE_componentWillMount() {
    const { getUsersManagers } = this.props;
    const { page, rowsPerPage } = this.state;
    getUsersManagers(page, rowsPerPage);
  }
  handleChangePage = (event, newPage) => {
    this.setState({ page: newPage });
  };

  handleChangeRowsPerPage = event => {
    this.setState({ rowsPerPage: +event.target.value });
    this.setState({ page: 0 });
  };

  render() {
    const columns = [
      { id: 'firstName', label: 'First Name', minWidth: 170, align: 'center' },
      { id: 'lastName', label: 'Last Name', minWidth: 100, align: 'center' },
      { id: 'email', label: 'User Email', minWidth: 170, align: 'center' },
      { id: 'role', label: 'Role', minWidth: 170, align: 'center' },
      { id: 'manager', label: 'Line Manager', minWidth: 170, align: 'center' },
    ];
    function createData(firstName, lastName, email, role, manager, id) {
      return { firstName, lastName, email, role, manager, id };
    }

    const { classes, userData } = this.props
    const rows = [];

    let user;
    let users = [];
    for (user in userData) {
      users.push(userData[user]);
    }
    users.map((user, index) => {
      rows.push(
        createData(
          user.firstName,
          user.lastName,
          user.email,
          user.role,
          user.manager,
          user.id
        ),
      );
    });
    return (
      (!userData) ? (<div>Loading, Please wait...</div>) :
        (<Paper className={classes.root}>
          <TableContainer className={classes.container}>
            <Table stickyHeader aria-label="sticky table">
              <TableHead>
                <TableRow>
                  {columns.map(column => (
                    < TableCell
                      key={column.id}
                      align={column.align}
                      style={{ minWidth: column.minWidth }}
                    >
                      {column.label}
                    </TableCell>
                  ))}
                </TableRow>
              </TableHead>
              <TableBody>
                {rows.map((row, index) => {
                  return (
                    <TableRow hover role="checkbox" tabIndex={-1} key={row.id}>
                      <TableCell align='center'>
                        {row.firstName}
                      </TableCell>
                      <TableCell align='center'>
                        {row.lastName}
                      </TableCell>
                      <TableCell align='center'>
                        {row.email}
                      </TableCell>
                      <TableCell align='center'>
                        {row.role}
                      </TableCell>
                      <TableCell align='center'>
                        <Autocomplete
                          {...userData}
                          id={row.firstName}
                          options={userData}
                          getOptionLabel={option => option.firstName}
                          style={{ fontSize: '5px' }}
                          renderInput={params => <TextField {...params} label={row.manager} margin="normal" fullWidth />}
                        />
                      </TableCell>
                    </TableRow>
                  );
                })}
              </TableBody>
            </Table>
          </TableContainer>
          <Button variant="contained" color="primary" style={{ fontWeight: 'bolder' }} disabled={this.state.isButtonDisabled}>Update</Button>
          <Button variant="contained" color="secondary" style={{ fontWeight: 'bolder' }} disabled={this.state.isButtonDisabled}>Cancel</Button>
          <TablePagination
            rowsPerPageOptions={[5, 10, 30]}
            component="div"
            count={rows.length}
            rowsPerPage={this.state.rowsPerPage}
            page={this.state.page}
            onChangePage={this.handleChangePage}
            onChangeRowsPerPage={this.handleChangeRowsPerPage}
          />
        </Paper >)
    );
  }
}

const mapStateToProps = state => {
  return {
    userData: state.userManagementReducer.userData
  }
}

export default connect(mapStateToProps, { getUsersManagers, getUsersAction })(withStyles(useStyles)(UserManagement));

My actions

export const getUsersManagers = (page, rowsPerPage) => async dispatch => {
   try {
      const headers = {
         'Content-type': 'application/json',
         'token': `Bearer ${localStorage.getItem('token')}`,

      }
      const users = await axios.get(`${process.env.BACKEND_BASE_URL}/api/v1/user-managements?page=${page}&limit=${rowsPerPage}`, { headers });
      dispatch(getUsersAction(users.data.data));
      // return {

      // }
   } catch (error) {
      return error;

   }
}

export function getUsersAction(data) {
   return {
      type: USERS_MANAGERS,
      payload: data
   }
}

My reducers

const initState = { userData: [] };
const userManagementReducer = (state = initState, action) => {

   switch (action.type) {

      case 'USER_MANAGER':

         return {
            ...state,
            userData: action.payload,
         }
      default: return state
   }
}
export default userManagementReducer;
  • Can we get a sample of the code that you're using to fetch the data from the API and the code you're using to access the response? – bwalshy Feb 20 '20 at 23:32
  • 1
    Welcome to Stackoverflow. Please remember to read our policies on [what is on topic here](/help/on-topic) but far more important for this question, the ["how do I ask a good question?"](/help/how-to-ask) article. Because if this is your entire question: what do you mean with "while trying to access the id"? Access how? Where's your code? – Mike 'Pomax' Kamermans Feb 20 '20 at 23:33
  • @Jordan you need to use the index for the array that is returned from your api like console.log(data[0].id); – Sunil Lama Feb 20 '20 at 23:44

0 Answers0