React. State does not change after change select

Your code has multiple ‘what’ factores for me. For once, you have an function called loadData, which performs a POST…

Another thing I saw, is;

<Select              
          options={dataList}
          onChange={onChange.bind(this)}
        />   

has a bind, I do not think that’s necessary, instead, I’d change it to be

<Select              
          options={dataList}
          onChange={onChange}
        />   

The main problem.

also, when you’re performing state changes, and then calling a function, the state change may not be updated when the fetch is called.

const onChange = (selectedOption) => {
    setMinPaid(parseInt(selectedOption.value));
    LoadData();
  };

So I think it’s better to pass that value to the LoadData function instead like this:

 const [dataList, setdataList] = useState([]);
  const [isLoding, setIsLoading] = useState(false);
  const [minPaid, setMinPaid] = useState(0);

  const dataSelectList = [
    { label: "2", value: "20000000" },
    { label: "3", value: "30000000" },
    { label: "4", value: "40000000" },
    { label: "5", value: "50000000" },
    { label: "10", value: "100000000" },
  ];

  const LoadData = (minPaid) => {
    setIsLoading(true);

    fetch("url", {
      method: "POST",
      headers: {
        Accept: "application/json",
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        paid: minPaid,
      }),
    })
      .then((response) => {
        return response.json();
      })
      .then((data) => {
        setIsLoading(false);
        if (data.success)
            setdataList(data.list);
      });
  };

  

  const onChange = (selectedOption) => {
    setMinPaid(parseInt(selectedOption.value));
    LoadData(parseInt(selectedOption.value));
  };

  return (
    <div>      
        <Select              
          options={dataList}
          onChange={onChange}
        />          
    </div>
  );

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top