hc-oss / react-multi-select-component

Lightweight (~5KB gzipped) multiple selection dropdown component
https://codesandbox.io/s/react-multi-select-example-uqtgs
MIT License
386 stars 89 forks source link

Component Options do not update when the state changes #438

Closed wongCH closed 3 years ago

wongCH commented 3 years ago

Describe the bug: When options state is updated, the dropdown do not show the new value.

To Reproduce:

import React, { useState } from "react";
import MultiSelect from "react-multi-select-component";
import "./styles.css";
export default function App() {
  const [selected, setSelected] = useState([]);
  const [options, setOptions] = useState([
    { label: "Grapes 🍇", value: "grapes" }
  ]);
  const AddOption = () => {
    setOptions([ { label: "Mango 🥭", value: "mango" },
    { label: "Strawberry 🍓", value: "strawberry" }
  ]);
  };
  return (
    <div>
      <h1>Select Fruits</h1>
      <p>{JSON.stringify(options)}</p>
      <MultiSelect
        options={options}
        value={selected}
        onChange={setSelected}
        labelledBy={"Select"}
      />
      <button onClick={AddOption}> Add option </button>
    </div>
  );
}

This only happens from version 4.0.2 onwards. No issue with version 4.0.1

Sample Code using Version 4.0.3 https://codesandbox.io/s/react-kerl-bug-0hm06?file=/src/App.js

Desired behaviour: When Option state changes, component should reflect the state just like in version 4.0.1

harshzalavadiya commented 3 years ago

@wongCH It looks like you are trying to print options instead of selected

it should be something like below

- <p>{JSON.stringify(options)}</p>
+ <p>{JSON.stringify(selected)}</p>

by making this change provided sandbox just works as expected

wongCH commented 3 years ago

Hi @harshzalavadiya ,

When page first load, the Option only have Grape:

Before

Picture above depicts the Option state that only contains "Grape" using version 4.0.3

To simplified my scenario,i wrote a function to overwrite the Option to the following: "[{"label":"Mango 🥭","value":"mango"},{"label":"Strawberry 🍓","value":"strawberry"}]"

Unfortunately, the dropdown component do not reflect the new values after i tried to add into the Option state

After

Picture above depicts the Option state been replace with Mango and strawberry but the Dropdown component still show Grape using version 4.0.3

Below is the picture when i change the version to 4.0.1 that work.

correct
harshzalavadiya commented 3 years ago

@wongCH my bad, yes you are right, I looked at different thing, I'll try to see and fix this

harshzalavadiya commented 3 years ago

@wongCH issue is fixed in latest release v4.0.4+

wongCH commented 3 years ago

@harshzalavadiya thank you so much.