简体   繁体   中英

React & Axios: Unable to render array values in UI but I can console.log them

I am trying to render an array of data on the UI. So far, I have been able to console.log the array but have not been able to display it on a table.

I am currently using Axios to retrieve the data from the back-end and am trying to render the data in Bootstrap Table. My initial issue was that I needed to assign each child in the list a unique key prop. Now that this error is gone, I still cannot see the data in the UI.

Invite table component (InviteTable.js):

import React, { useState, useEffect } from 'react';
import Axios from 'axios';
import BootstrapTable from 'react-bootstrap-table-next';
import PaginationFactory from 'react-bootstrap-table2-paginator';
import ToolkitProvider, {Search} from 'react-bootstrap-table2-toolkit/dist/react-bootstrap-table2-toolkit';
import Spinner from 'react-bootstrap/Spinner';

const InviteTable = () => {

    const [invites, setInvites] = useState([]);
    const [loading, setLoading] = useState(false);
    const { SearchBar } = Search;
    const url = "http://localhost:5000/api/get";

    //Define columns
    const columns = [
        { dataField: "Id", text: "Id", headerStyle: () => {return { width: "10%" };} },
        { dataField: "Code", text: "Invite Code", headerStyle: () => {return { width: "10%" };} },
        { dataField: "Recipient", text: "Recipient Email", headerStyle: () => {return { width: "35%" };}  },
        { dataField: "Created", text: "Date Sent", headerStyle: () => {return { width: "35%" };}  },
    ];

    //GET and set data
    useEffect(() => {
        Axios.get(url).then(result => {
            setInvites(result.data);
            console.log(result.data);
            setLoading(true);
        })
        .catch(function(error) {
            console.log(error);
          });
    }, []);

    return (
        <div>
            {loading ? (
                  <ToolkitProvider keyField="Id" data={invites} columns={columns} search>
                {(props) => (
                    <div>
                        <SearchBar {...props.searchProps} />
                        
                        <BootstrapTable
                        {...props.baseProps}
                        pagination={PaginationFactory()}
                        />
                    </div>
                )}
                </ToolkitProvider>                  
            ) : (
                <Spinner animation="border" />
            )}
        </div>
    )
};

export { InviteTable }

Console: Output of console.log

I have resolved this issue. The problem lay in the server file that was running the query to return the invites.

I am quite new to this so am still in the process of learning as I go.

Initially I was sending the entire result to the front end which was causing issues:

request.query('select * from Invites;', (err, result) => {
            
            // console log error if there is one
            if (err) console.log(err);

            // send records as a response
            res.send(result);
            
        });

To resolve this, I specified that the recordset should be sent to the front end:

request.query('select * from Invites;', (err, result) => {
            
            // console log error if there is one
            if (err) console.log(err);

            // send records as a response
            res.send(result.recordset);
            
        });

Here is the solution, first check your data if it's in the object then convert it into an array. and make sure your columns' dataField name same as your database parameters

const [post, setPost] = useState([]);

then(response => {
      const data = response.data;
      const arr = Object.entries(data); //convert object into array
      arr.forEach(([key, value]) => {
      setPost(oldArray => [...oldArray, value]); // Assign Data toTable 
        
      });
    })

 <BootstrapTable keyField='id' data={post} columns={columns} pagination={paginationFactory()}/>

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