I have a parent components which also have two child components(table and chart) and both components need data from request. But if i set request in parent components i must pass data across children to table and have table elements style.
for example
`
const Row = styled.tr''
const Td = styled.td''
export default function() {
const [datasets, setDatasets] = useState(null);
const { pages, pageSWRs, isEmpty, isLoadingMore, isReachingEnd, loadMore } = useSWRPages(
'statistic-page',
({ offset, withSWR }) => {
const { data, error } = withSWR(
useSWR(// make request),
);
if (error) return null;
if (!data) return '...loading';
setDatasets(data)
return data.map(item => (
<Row key={item.date}>
{Object.keys(item).map(key => (
<Td>{item[key]}</Td>
))}
</Row>
));
},
({ data }, index) => {
return data && data.length === LIMIT ? (index + 1) * LIMIT : null;
},
[],
);
return (
<>
<Chart data={datasets} />
<Table>
{pages}
<Table/>
</>
);
}
`
The question is next: Have i'm trying use swr wrong and how it must be?
Hi @VivatRafa! First, in your case I saw the undocumented useSWRPages, I need to point out that it's _specifically_ for infinite loading (not the normal pagination cases), and the API might change in the future.
And about your question, I would organize the code like this:
import useSWR from 'swr'
export default function() {
const { pages, pageSWRs } = useSWRPages(
'statistic-page',
({ offset, withSWR }) => {
const { data, error } = withSWR(
useSWR(// make request),
);
// let's render nothing inside `pages`
return null;
},
({ data }, index) => {
return data && data.length === LIMIT ? (index + 1) * LIMIT : null;
},
[],
);
// we get everything from pageSWRs
const datasets = pageSWRs.map(swr => swr.data);
return (
<>
{pages}
<Chart data={datasets} />
<Table>
{datasets.map(data => {
return data.map(item => (
<Row key={item.date}>
{Object.keys(item).map(key => (
<Td>{item[key]}</Td>
))}
</Row>
));
})}
<Table/>
</>
);
}
Keep in mind that pageSWRs is just an array of your SWR results (and it's important that you still have to render pages even if it's empty). So you can do any manipulations like const datasets = pageSWRs.map(swr => swr.data);.
@shuding thank you for your answer!
Most helpful comment
Hi @VivatRafa! First, in your case I saw the undocumented
useSWRPages, I need to point out that it's _specifically_ for infinite loading (not the normal pagination cases), and the API might change in the future.And about your question, I would organize the code like this:
Keep in mind that
pageSWRsis just an array of your SWR results (and it's important that you still have to renderpageseven if it's empty). So you can do any manipulations likeconst datasets = pageSWRs.map(swr => swr.data);.