Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

react-admin

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>
like image 322
sunfly Avatar asked Jul 29 '19 03:07

sunfly


1 Answers

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())
}, [])
like image 86
Michael Avatar answered Nov 14 '22 07:11

Michael