import React, { useState, useEffect } from 'react';

function ObjEqual(a, b) {
  if (typeof(a) !== 'object' || typeof(b) !== 'object') {
    return false
  }

  return JSON.stringify(a) === JSON.stringify(b)
}

export function useQuery(params, request) {
  const [preParams, setParams] = useState({})
  const [data, setData] = useState({})
  const [error, setError] = useState()
  const [loading, setLoading] = useState(false)

  useEffect(() => {
    if (ObjEqual(preParams, params)) {
      return
    }

    setLoading(true)
    setParams(params)
    request(params).then((res) => {
      setData(res)
      setError(void 0)
      setLoading(false)
    }).catch((err) => {
      setError(err)
      setLoading(false)
    })
  })

  return [
    data,
    loading,
    error,
  ]
}
