简体   繁体   中英

How to solve Error adding Fetched data to react table?

I'm making a table that fetches the data from the backend and then displays it in frontend.

What I'm doing is -> fetch data,useState,use the useState on ReactMemo,but I'm unable to make it work.

When I try to run this and print the data, I get it blank,when I print loaded state,it to comes undefined but when I console the things(ti.e, response prints the values that I wanted)

import React,{useEffect,useState} from 'react'
import styled from 'styled-components'
import { useTable } from 'react-table'
import { useHttpClient } from '../../shared/hooks/http-hook';

function Table({ columns, data }) {
// Use the state and functions returned from useTable to build your UI
  const {
  getTableProps,
  getTableBodyProps,
  headerGroups,
  rows,
  prepareRow,
    } = useTable({
       columns,
       data,
     })


    // Render the UI for your table
  return (
    <table {...getTableProps()}>
      <thead>
        {headerGroups.map(headerGroup => (
          <tr {...headerGroup.getHeaderGroupProps()}>
            {headerGroup.headers.map(column => (
              <th {...column.getHeaderProps()}>{column.render('Header')}</th>
            ))}
          </tr>
        ))}
      </thead>
      <tbody {...getTableBodyProps()}>
        {rows.map((row, i) => {
          prepareRow(row)
          return (
            <tr {...row.getRowProps()}>
              {row.cells.map(cell => {
                return <td {...cell.getCellProps()}>{cell.render('Cell')}</td>
              })}
            </tr>
          )
        })}
      </tbody>
    </table>
  )
}
function Group() {
  const columns = React.useMemo(
    () => [
      {
        Header: 'Name',
        columns: [
          {
            Header: 'My Groups',
            accessor: 'groupId',
          },   
        ],
      },
    ],
    []
  );
  const {sendRequest} = useHttpClient();
  const [loadedUsers, setLoadedUsers] = useState();

  useEffect(() => {
    const fetchUsers = async () => {
      try {
        const responseData = await sendRequest(
          'http://localhost:5000/api/users/account/60fbf1b17b7fdc5ac0aa000e'
        );
        responseData.data.groups = responseData.data.groups.map((val)=>{return {
          'groupId':val
        }})
        const dataResponse = responseData.data.groups;
        setLoadedUsers(dataResponse);

      } catch (err) {}
    };
    fetchUsers();
  }, [sendRequest]);

      var data = React.useMemo(() => loadedUsers, []);
    console.log(data)
      return (
        <Styles>
          
          <Table columns={columns} data={data} />
        
        </Styles>
      )
  }

  export default Group

You've to use loadedUsers as dependency array of useMemo

replace

var data = React.useMemo(() => loadedUsers, []);

with this

 var data = React.useMemo(() => loadedUsers, [loadedUsers]);

You can do it like this.

Also, you don't even need to memoize data. Instead, I think you can pass loadedUsers as it is for table data prop.

Let me know if it helps.

If you are using linting in your project, then you can add this plugin it will give you warning if you missed any dependency array values.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM