import { useEffect, useState } from 'react'

function checkStatus(response) {
  if (response.status >= 200 && response.status < 300) {
    return response
  } else {
    const message =
      'Fetch error: ' + response.url + ' ' + response.status + ' (' +
      response.statusText + ')'
    const error = new Error(message)
    error.response = response
    throw error
  }
}

export function useGetJson(url) {
  const [data, setData] = useState(null)
  useEffect(() => {
    if (url) {
      let ignore = false
      fetch(url)
        .then(checkStatus)
        .then(response => response.json())
        .then(json => {
          if (!ignore) {
            setData(json)
          }
        })

      return () => { ignore = true }
    }
  }, [url])

  return data
}

export function usePostForm(url, formData) {
  const [data, setData] = useState(null)
  useEffect(() => {
    if (url) {
      let ignore = false
      fetch(url, {
        method: 'POST',
        body: formData
      }).then(checkStatus)
        .then(response => response.json())
        .then(json => {
          if (!ignore) {
            setData(json)
          }
        })
        .catch(error => {
          throw error
        })

      return () => { ignore = true }
    }
  }, [url])

  return data
}