Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How undo setState if Fecth was failed?

Im trying change state and if internet connection lost. Component renders new state, but it doesn’t changed on server. How i can undo last setState to prevent state change?

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>
  )
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You can use useRef hook to save previous position, for example:

const Position = ({ value }) => {
  const [position, setPosition] = useState(value)
  // useRef here
  const prevPosition = useRef(value)

  useEffect(() => {
    async function fetchData() {
      try {
        const { position } = await changePosition(position)
        // if success save new position and do something you want.
        prevPostion.current = position
        
      } catch (e) {
        console.log(e)
        // if fail setState to previous position.
        setPosition(prevPosition)
      }
    }

    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>
  )
}

Hope to help you !

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading