0

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"));

1 Answer 1

1

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

<ReactTable
  data={data.getTemplates}
  columns={columns}
  defaultPageSize={10}
/>
Sign up to request clarification or add additional context in comments.

2 Comments

And I thought that I had checked for all the typos :( thank you!
Happy to help :) I highly recommend you use a linter (eslint) with airbnb config. It solves a lot of issues like these.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.