0

I have a rather simple question on using react-table from React.js.

I cannot find any samples nor documents regarding useMemo for a local json, pretty much all of the tutorials are based on asyn api.

The objective is to create a table as such: https://codesandbox.io/s/github/tannerlinsley/react-table/tree/master/examples/pagination?file=/src/App.js

The only difference between the tutorial and mine, is the makeData file would be an actual json file with legit data.

This is what I tried:

  const data = React.useMemo(() => Sales, [])

which obviously did not work, and sent back TypeError: Cannot read property 'forEach' of undefined.

How should I approach this?

2 Answers 2

1

It looks like useMemo expects the data to be formatted as an array containing objects, versus the raw json format you're currently providing.

Importing the JSON

Depending on modules available, either use the built in json loader, or wrap your json file inside a ts/js file e.g.

const Data = { "thing": "value }
export default Data

and import via

import jsonData from './data.json'

Processing the JSON

There may be a more elegant way to do this, In this case, I was able to get something working by creating a helper function to preprocess the data. It just takes advantage uses keys/map to iterate over the JSON and stuff each value into an array.

function processData(jsonData) {
  const result = Object.keys(jsonData).map((key) => { 
    return jsonData[key];
  });
  return result;
}

so, from the example you provided instead of

const data = React.useMemo(() => makeData(100000), []);

the line is

const data = React.useMemo(() => processData(jsonData), []);
Sign up to request clarification or add additional context in comments.

Comments

0

The error message:

TypeError: Cannot read property 'forEach' of undefined

is caused by not adding the "rows" property beneath the function Table, add rows, and pages. Add rows under page, along with:

const data = React.useMemo(() => processData(jsonData), []);

and:

function processData(jsonData) {
  const result = Object.keys(jsonData).map((key) => {return jsonData[key]; });
  return result;
}

Comments

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.