// import React, {useState, useEffect} from "react";
// import axios from "axios";

// const useFetch = (url) => {
//     const [loading, setLoading] = useState(false);
//     const [data, setData] = useState({});
//     const [error, setError] = useState();

//     useEffect(() => {
//         if (!url) return;
//         setLoading(true);

//         axios
//       .get(url)
//       .then(res => {
//         setData(res.data.data.attributes);
//         //console.log(res.data.data.attributes);
//         setLoading(false);
//       })
//       .catch(err => {
//         console.log(err);
//         setError(err);
//         setLoading(false);
//       });
//     }, [url]);

//     return { data, loading, error };
// };

// export default useFetch;


import axios from 'axios'
import React, {useEffect, useReducer} from 'react'

const initialState = {
  loading: true,
  post: {},
  error: ''
}

const reducer = (state, action) => {
  switch (action.type) {
    case 'FETCH_DATA_SUCCESS':
      return {
        ...state,
        loading: false,
        post: action.payload.data,
        error: ''
      }      
    case 'FETCH_DATA_FAILURE':
      return {
        ...state,
        loading: false,
        post: {},
        error: action.payload.error
      }
  
    default:
      return {...state}
  }
}



export default function useFetch() {
  const [state, dispatch] = useReducer(reducer, initialState)
  const {loading, post, error} = state
  useEffect(() => {
    axios
      .get('https://jsonplaceholder.typicode.com/posts/1')
      .then(response => {
        dispatch({
          type: 'FETCH_DATA_SUCCESS',
          payload: { data: response.data }
        })
      })
      .catch(error => {
        dispatch({
          type: 'FETCH_DATA_FAILURE',
          payload: { error: error.message }
        })
      })
  }, [])

  const renderPost = post => {
    return (
      <>
        <b>Response: </b>
        {post.title}
      </>
    )
  }

  return (
    <>
      {loading ? 'Loading' : renderPost(post)}
      {error ? error : null}
    </>
  )
}
