'Load Mantine MultiSelect data when dropdown first opened

I'd like to use Mantine's MultiSelect but only fetch from the server the dropdown data the first time users open the dropdown.

Most obvious candidate seems to be the onDropdownOpen where I could fetch the data but I don't know how to reference the element and its data in there. Thought I could reference it, but the code at the bottom on the doc as copied below doesn't compile (doesn't like the brackets after HTMLInputElement):

import { useRef } from 'react';
import { MultiSelect } from '@mantine/core';

function Demo() {
  const ref = useRef<HTMLInputElement>();
  return <MultiSelect ref={ref} data={[]} />;
}

Being very new to React, I feel I'm missing the obvious here so it'd be great if you could point me in the right direction.



Solution 1:[1]

I finally came up with this which seems to work. Would love to have some feedback as I stated above, I'm a begginer with React and coming from simple javascript it's a bit hard adapt to the philosophy.

import React, { useState, useEffect  } from 'react';
import { MultiSelect, Loader } from '@mantine/core';

export default function MyDropDown() {
    const [data, setData] = useState(null);
    const [opened, setOpened] = useState(false);

    useEffect(() => {
        if (opened) {
            fetch("https://www.someapi.com")
            .then(response => response.json())
            .then(json => {
                setData(json);
            });
        }
    }, [opened]);
    return (
        <MultiSelect 
            data={data || []} 
            nothingFound={data && "Nothing here"} 
            onDropdownOpen={() => setOpened(true)} 
            rightSection={!data && opened && <Loader size="xs" />}
        />
    );
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Johann