0

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.

Johann
  • 12,158
  • 11
  • 62
  • 89

1 Answers1

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" />}
        />
    );
}
Johann
  • 12,158
  • 11
  • 62
  • 89