-
Notifications
You must be signed in to change notification settings - Fork 0
/
ImageSearchViewModel.js
44 lines (38 loc) · 1.25 KB
/
ImageSearchViewModel.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import { useState, useEffect } from 'react';
import axios from 'axios';
const apiUrl = 'https://api.unsplash.com/search/photos/';
const ACCESS_KEY = "fEx0f6fugNGVNZ2AwARl7_wG8gr8zWAoIQkLUOpmEmE";
const useImageSearch = () => {
const [images, setImages] = useState([]);
const [searchHistory, setSearchHistory] = useState([]);
const fetchAPI = async (query) => {
try {
const queryString = `?query=${query}&client_id=${ACCESS_KEY}`;
const fullUrl = apiUrl + queryString;
const response = await axios.get(fullUrl);
const imageData = response.data.results;
const imageDetailsPromises = imageData.map(async (item) => {
return {
id: item.id,
url: item.urls.regular,
title: "Titulo: " + item.alt_description || 'Sin título',
author: "Autor: " + item.user.name || 'Autor desconocido',
};
});
const imageDetails = await Promise.all(imageDetailsPromises);
setImages(imageDetails);
setSearchHistory((prevHistory) => [query, ...prevHistory]);
} catch (error) {
console.error('Error fetching data:', error);
}
};
useEffect(() => {
fetchAPI();
}, []);
return {
images,
searchHistory,
fetchAPI,
};
};
export default useImageSearch;