Fetch data only the first time go to a Tab in a TabbedForm
Asked Answered
S

1

11

I have a tabbed form that the second tab will retrieve a list from the backend, similar to the react-admin official demo (e.g. post has many comments). The problem is when I switch the tab, there is always a backend call for the second tab which is comment list. How can I avoid it and just load one time? Because I have pagination on the second tab, if I switch tab, the pagination will be changed to the first page.

Thank you in advance!

<TabbedForm>
    <FormTab label="Post">
        <TextInput source="name"/>
    </FormTab>

    <FormTab label="Comment">
        {/* This tab should fetch data only once if I switch tabs */}
        <ReferenceManyField
            pagination={<Pagination/>}
            reference="comments"
            target="id"
            perPage={5}
            addLabel={false}
        >
            <Datagrid>
                <TextField source="name" />
                <EditButton />
                <DeleteButton undoable={false}/>
            </Datagrid>
        </ReferenceManyField>
    </FormTab>
</TabbedForm>
Sabin answered 29/7, 2019 at 3:23 Comment(2)
Can you show your logic for fetching the data?Micamicaela
Not very sure if this can be implemented... Perhaps adding a counter, and only loading the data when that counter is 0 via conditional. joshblog.net/2018/conditional-rendering-with-react-and-jsx or github.com/marmelab/react-admin/issues/2548 perhaps help.Selfsufficient
M
1

If you are using Hooks, you could use a combination of useState and useEffect. useState would hold the result of your data-fetching, which you would trigger in useEffect. To make that happen just once, use an empty array as dependency-array in useEffect:

const [data, setData] = useState(null)

useEffect(() => {
  setData(fetchData())
}, [])
Marji answered 11/8, 2019 at 10:17 Comment(1)
Can you describe a full code sample to make it works with the specific case of the TabbedForm? It seems pretty simple to award a bounty.Alyworth

© 2022 - 2024 — McMap. All rights reserved.