简体   繁体   中英

Pass array from GraphQL query to React-Table

I am trying to take the array output of a GraphQL query and render it using React-Table but I am getting a Cannot read property 'forEach' of undefined error.

The only other question similar to mine that I have managed to find has not helped ( How to show data from GraphQL server to npm react-table? ). When I printed the query result to the console it looks like a normal array to me so I am not sure why forEach does not recognise it.

Component code:

import React from 'react';
import { Query } from 'react-apollo';
import gql from 'graphql-tag';

import ReactTable from 'react-table';
import "react-table/react-table.css";

const getTemplatesQuery = gql`
{
    getTemplates {
        id
        name
    }
}
`;

const columns = [
    {
        Header: "ID",
        accessor: "id"
    },
    {
        Header: "Name",
        accessor: "name"
    }
];

const Templates = () => (
    <Query 
        query = {getTemplatesQuery}>
        {({ loading, error, data }) => {
            if (loading) return <p>Loading...</p>;
            if (error) return <p>error</p>;

            // return data.getTemplates.map(({ id, name }) => (
            //     <p key={id} >{`${name}`}</p>
            // ));

            console.log(data);

            return (
                <div>
                    <ReactTable>
                        data = { data.getTemplates }
                        columns = { columns }
                        defaultPageSize = { 10 }
                    </ReactTable>
                </div>
            );
        }}
    </Query>
)

export default Templates;

App code:

...
class App extends Component {
    render() {
        return (
            <ApolloProvider client={client}>
            <div>
                <h2>My first Apollo app</h2>
                <Templates />
            </div>
        </ApolloProvider>
        );
    }
}

render(<App />, document.getElementById("root"));

Your syntax for react table is wrong, it should be something like this

<ReactTable
  data={data.getTemplates}
  columns={columns}
  defaultPageSize={10}
/>

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