I
I
Im p3l2022-02-14 10:47:31
React
Im p3l, 2022-02-14 10:47:31

How to return state to the previous value on unsuccessful fetch?

Please tell me how can I return the state to the previous value when sending to the server fails?

const Position = ({ value }) => {
  const [position, setPosition] = useState(value)

  useEffect(() => {
    async function fetchData() {
      try {
        const { position } = await changePosition(position)
        setPosition(position)
      } catch (e) {
        console.log(e)
      }
    }

    fetchData()
  }, [position])

  return (
    <Select
      value={position}
      onChange={(value) => setPosition(value)}
    >
      <Option value="left">Left</Option>
      <Option value="top">Top</Option>
      <Option value="right">Right</Option>
      <Option value="bottom">Bottom</Option>
    </Select>
  )
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
K
kookoo, 2022-02-14
@LoranDeMarcus

If you need access to the previous value, then
https://reactjs.org/docs/hooks-faq.html#how-to-get...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question