0

I know that it's repeat, but i don't understand how to fix it in my case I send put request to server, but it has old value, what i should do?

React code:

const [sizeValue, setSizeValue] = useState(basketItem.clotheSize)
<select
   name={"size"}
   className={"sizeSelector"}
   value={sizeValue}
   onChange={e => {
      setSizeValue(e.target.value)
      updateClothesSize(basketItem.id, sizeValue)
   }}
>
  <option value="s">s</option>
  <option value="m">m</option>
  <option value="l">l</option>
  <option value="xl">xl</option>
  <option value="xxl">xxl</option>
</select>

axios code:

export const updateClothesSize = async (id, size) => {
    const {data} = await $host.put('api/basket/' + id, {clothesSize: size})
    return data
}
DRx
  • 21
  • 4
  • 1
    `setSizeValue` *does not* immediately change the value of `sizeValue` in the context which it is called. Instead, it triggers a re-render where the new value of `sizeValue` is available. Just use `e.target.value` or use a `useEffect` separately. – crashmstr Jan 04 '23 at 16:25
  • Just use e.target.value in update cloth size – Wiktor Zychla Jan 04 '23 at 16:25
  • Also https://stackoverflow.com/q/41446560/1441 – crashmstr Jan 04 '23 at 16:26

1 Answers1

3

useState will not update the state value immediately. You can fix your issue by either directly passing the value to updateClothesSize(basketItem.id, e.target.value).Or use a useEffect in which you'll call updateClothesSize.

useEffect(() => {
  updateClothesSize(basketItem.id, sizeValue)
},[sizeValue])