0

I'm trying to map over an array that I get from parent component but the problem is that even though I assign the data to state, on the initial load state is empty and that results me having an empty array. I need this array in the state because I will be implementing a sorting functionality into my project and I would like to change userData whenever user clicks on corresponding cell. Here is the code I have :

import React, { useState } from 'react';
import { Table } from 'semantic-ui-react';
import Moment from 'react-moment';
const UserTable = ({ repoData }) => {
    const [userData, setUserData] = useState(repoData);
    console.log(repoData)

    const descending = [].concat(repoData)
        .sort((a, b) => a.name < b.name ? 1 : -1);

    const ascending = [].concat(repoData)
        .sort((a, b) => a.name > b.name ? 1 : -1);

    function clickHandler() {
        setUserData(descending)
    }
    return (
        <div>
            <Table sortable celled fixed>
                <Table.Header>
                    <Table.Row>
                        <Table.HeaderCell
                            onClick={clickHandler}
                        >
                            Repository Name
        </Table.HeaderCell>
                        <Table.HeaderCell

                        >
                            Description
        </Table.HeaderCell>
                        <Table.HeaderCell

                        >
                            Created At
        </Table.HeaderCell>
                    </Table.Row>
                </Table.Header>
                <Table.Body>
                    {userData.map(repos => {
                        return <Table.Row>

                            <Table.Cell>{repos.name}</Table.Cell>
                            <Table.Cell>{repos.description}</Table.Cell>
                            <Table.Cell> <Moment format="DD-MM-YYYY">{repos.created_at}</Moment></Table.Cell>
                        </Table.Row>
                    })}


                </Table.Body>
            </Table>
        </div>
    );
}

export default UserTable;

em_code
  • 379
  • 5
  • 17

1 Answers1

1

Since the first logs are empty this means that the parent component passes an empty array to UserTable.

If you dont want UserTable to show when repoData is still empty, you can do that at the parent level by checking that repoData is defined and has a length > 0.

const App = () => {
  ...

  return (
      <>
          ...
          {repoData && repoData.length ? <UserTable repoData={repoData} /> : null (or something else)}
          ...
      </>
  )
}
Hamza El Aoutar
  • 5,292
  • 2
  • 17
  • 23