-1

i need some help with setstate asynchronous.

i have this select

<select id='province'  onChange={handleProvince}>
                    <option>Select Province</option>
                    {province?.map(province=>(
                        <option value={province.id}>{province.name}</option>
                    ))}
 </select>

and this is the onchange function

function handleProvince(e){
    setProvinceID(e.target.value)
    axios.get(`http://192.168.18.46/api/regency/${provinceID}`).then((res)=>{
      setRegency(res.data.data)
    })
  }

putting the setProvinceID(e.target.value) in the same function causes me to change the select element twice for it to pick the value.

how do i anticipate it?

any help would be much appreciated, thanks

pandu
  • 65
  • 5
  • so i put ```setProvinceID(e.target.value)`` in the useEffect, and set the provinceID as dependencies? – pandu Nov 09 '22 at 09:33
  • Never do this, **Never set in a useEffect hook a dependency of the same hook** you'll send the browser into a frenzy. A dependency useEffect should set a state depending on another state or set of states but not itself. @pandu – xodeeq Nov 09 '22 at 10:02

2 Answers2

2

Try something like it:

const handleProvince = ({ target }) => (
    axios.get(`http://192.168.18.46/api/regency/${target?.value}`).then(({ data }) => {
      setProvinceID(target.value);
      setRegency(data?.data);
    })
  );

Paul-Marie
  • 874
  • 1
  • 6
  • 24
0

Remove the async call from the eventHandler and use it as a dependent a useEffect hook, everytime the provinceID gets set, the call is made right after.

// I imagine this is what your state declaration looks like
const [provinceID, setProvinceID] = useState("");

function handleProvince(e){
    setProvinceID(e.target.value)
 }

useEffect(() => {
    axios.get(`http://192.168.18.46/api/regency/${provinceID}`)
    .then((res)=>{
      setRegency(res.data.data)
    })
}, [provinceID])

I had imagined that you were working with a react functional component also what your state declaration would be like, both inference made from your use of setProvinceID.

xodeeq
  • 66
  • 4