Skip to content

Instantly share code, notes, and snippets.

@dmitriyzyuzin
Last active March 2, 2021 15:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dmitriyzyuzin/1fb67a5e59b64a49a37f109d6223b793 to your computer and use it in GitHub Desktop.
Save dmitriyzyuzin/1fb67a5e59b64a49a37f109d6223b793 to your computer and use it in GitHub Desktop.
Handle response using Fetch

Fetch handle response

Variant 1

const requestOptions = {
    mode: 'cors',
    headers: {
      'Content-Type': 'application/json',
      'Access-Control-Allow-Origin': '*'
    }
  }

const handleResponse = response => {
    const jsonResponse = response.json()
    if (response.ok) {
      return jsonResponse
    } else {
      return jsonResponse.then(err => { throw err })
    }
}

const get (url) {
    return fetch(url, requestOptions)
      .then(handleResponse)
  }

Variant 2

asyncAction()
      .then((resp) => {
        respStatus = resp.status
        return resp.json()
      })
      .then((resp) => {
        switch (respStatus) {
          case 200:
            // some logic
            break
          case 422:
            // validation logic
            break
          default:
            if (resp.message) {
                // if your api sends errors like {message: "you did wrong"}
              setErrorsHandler([resp.message])
            } else {
              throw new Error(resp)
            }
        }
      })
      .catch((err) => {
        setErrors([err.message])
        console.log('err: ', err)
      })
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment