jxom/bumbag-ui

Multiple SelectMenu inputs loadOptions not working as expected

ivantacca opened this issue · 2 comments

Hi guys,
I've just created a form component with two SelectMenu inputs on it, each one having its own loadOptions

Expeceted behaviour:
Each SelectMenu should load and display its own options.

Actual behaviour:
Only the first SelectMenu loads the options. The getEpisodes callback is not executed and the second SelectMenu "inherits" the options loaded by the first one

Am I doing something wrong?

const Form = (props) => {
  const [character, setCharacter] = useState(null);
  const [episode, setEpisode] = useState(null);

  const getCharacters = React.useCallback(async () => {
    return fetch(`https://rickandmortyapi.com/api/character`)
      .then((res) => res.json())
      .then(({ results }) => ({
        options: results.map((character) => ({
          key: character.id,
          label: character.name,
          value: character
        }))
      }))
      .catch((err) => ({ options: [] }));
  }, []);

  const getEpisodes = React.useCallback(async () => {
    return fetch(`https://rickandmortyapi.com/api/episode`)
      .then((res) => res.json())
      .then(({ results }) => ({
        options: results.map((episode) => ({
          key: episode.id,
          label: episode.name,
          value: episode
        }))
      }))
      .catch((err) => ({ options: [] }));
  }, []);

  return (
    <div style={formStyle}>
      <SelectMenu
        placeholder="Characters"
        value={character}
        onChange={setCharacter}
        loadOptions={getCharacters}
      />
      <SelectMenu
        placeholder="Episodes"
        value={episode}
        onChange={setEpisode}
        loadOptions={getEpisodes}
      />
    </div>
  );
};

Codesandbox
https://codesandbox.io/s/bumbag-select-menu-3zmzo

jxom commented

Heya... Can you try add a unique cacheKey as a prop to each SelectMenu?
This is actually a bug in Bumbag, and we will need to make a unique instance of cacheKey for each SelectMenu... I'll tag this as a bug for now. But check out this CodeSandbox with the fix: https://codesandbox.io/s/bumbag-select-menu-forked-ygohf

Hey @jxom , thank you! Of course that solved my problem.

My fault, It was even in the documentation:
https://bumbag.style/form/select-menu/#fetching-data-async

<SelectMenu
  cacheKey="characters"
  placeholder="Characters"
  value={character}
  onChange={setCharacter}
  loadOptions={getCharacters}
/>