Ra-data-simple-rest is not working | ERROR: total is not a number and newRecords.forEach is not a function

Viewed 919

I am trying to follow the tutorial and I am now at the part where I have to implement my own REST-API. My format is identical to the needed format described in the tutorial. Here my response: The response from my API

The needed format looks like this:

// {
//     data: [
//         { id: 126, title: "allo?", author_id: 12 },
//         { id: 127, title: "bien le bonjour", author_id: 12 },
//         { id: 124, title: "good day sunshine", author_id: 12 },
//         { id: 123, title: "hello, world", author_id: 12 },
//         { id: 125, title: "howdy partner", author_id: 12 },
//     ],
//     total: 27
// }

But for some reason I always get the error that (1) total is not a number, but postman says it is. And (2) that newRecords.forEach is not a function.

´´´

//App.js
import logo from './logo.svg';
import React from 'react';
import { Admin, Resource, ListGuesser } from 'react-admin';
import simpleRestProvider from 'ra-data-simple-rest';
import styles from './App.css';
import SimpleFlow from './diagramm';
import { RuleList, PostList} from './rules';

//http://jsonplaceholder.typicode.com'
const dataProvider = simpleRestProvider('http://localhost:3000/api');
const App = () =>
    <Admin dataProvider={dataProvider} dashboard={SimpleFlow}>
        <Resource name="rules" list={RuleList} />
    </Admin>;

export default App;

´´´

´´´

//rules.js
import React from 'react';
import { List, Datagrid, TextField, EmailField, DateField, Pagination } from 'react-admin'; 

export const RuleList = (props) => (
    <List {...props} perPage={25}>
        <Datagrid rowClick="edit">
            <TextField source="id" />
            <TextField source="Bezeichnung" />
        </Datagrid>
    </List>

);

´´´

3 Answers

The problem is due to your data sample format, in that case your API respose it is an object, but it need to be an array instead. Like this:

[
     { id: 126, title: "allo?", author_id: 12 },
     { id: 127, title: "bien le bonjour", author_id: 12 },
     { id: 124, title: "good day sunshine", author_id: 12 },
     { id: 123, title: "hello, world", author_id: 12 },
     { id: 125, title: "howdy partner", author_id: 12 }
]

perhaps you re trying to render the data when it is still fetching. && render the data

The problem is that the documentation is a bit confusing. In some places it says it wants the "total" and "success" properties in the response, and some places just the array. At the end is just a matter of adjusting the response. In my case I just took the "total" off the response and it works perfectly.

Related