I am currently working on a little project that involves me using react memo with an external package(react-tables). slight hiccup being that some of the data to be used for the table data is gotten from an API and it throws an error on first load. What would be an ideal way to correct this error?
//react tables docs sort of requires the data be memoized, I think.
const data = React.useMemo(
() => [
{
col0: 1,
col1: `${items[0].name} ${items[0].symbol}`, //items values are gotten from state
col2: items[0].price,
col3: `${items[0]['1d'].price_change_pct * 100}%`,
col4: <ChartTable />,
},
{
col0: 2,
col1: `${items[1].name} ${items[1].symbol}`,
col2: items[1].price,
col3: `${items[1]['1d'].price_change_pct * 100}%`,
},
{
col0: 3,
col1: `${items[2].name} ${items[2].symbol}`,
col2: items[2].price,
col3: `${items[2]['1d'].price_change_pct * 100}%`,
},
{
col0: 4,
col1: `${items[3].name} ${items[3].symbol}`,
col2: items[3].price,
col3: `${items[3]['1d'].price_change_pct * 100}%`,
},
],
[],
);
const columns = React.useMemo(
() => [
{ Header: '#', accessor: 'col0' },
{
Header: 'Name',
accessor: 'col1', // accessor is the "key" in the data
},
{
Header: 'Price',
accessor: 'col2',
},
{
Header: 'Change',
accessor: 'col3',
},
{
Header: 'Chart',
accessor: 'col4',
},
],
[],
);
const { getTableProps, getTableBodyProps, headerGroups, rows, prepareRow } = useTable({ columns, data });
//the code is table is then rendered
On first load, it throws an error,can't read property 'name' of undefined, which is definitely cause items not defined at that point. If the said data is however defined before the table is to be rendered, it works as it should. So the problem is really finding a way to delay the calling of the data function on first render.
Is there an acceptable workaround for this issue?
PS: So far, if they aren't memoized, it throws an an internal error from the react tables code itself cant read property forEach
of undefined
It's deceptively simple.
If there are no items (for example), React.useMemo
should return an empty array.
The second part is that items
is a dependency of React.useMemo
* - don't forget to add it to the dependency array at the end of the hook:
//react tables docs sort of requires the data be memoized, I think.
const data = React.useMemo(
() => !items.length ? [] : [
{
col0: 1,
col1: `${items[0].name} ${items[0].symbol}`, //items values are gotten from state
col2: items[0].price,
col3: `${items[0]['1d'].price_change_pct * 100}%`,
col4: <ChartTable />,
},
{
col0: 2,
col1: `${items[1].name} ${items[1].symbol}`,
col2: items[1].price,
col3: `${items[1]['1d'].price_change_pct * 100}%`,
},
{
col0: 3,
col1: `${items[2].name} ${items[2].symbol}`,
col2: items[2].price,
col3: `${items[2]['1d'].price_change_pct * 100}%`,
},
{
col0: 4,
col1: `${items[3].name} ${items[3].symbol}`,
col2: items[3].price,
col3: `${items[3]['1d'].price_change_pct * 100}%`,
},
],
[items],
);