I'm trying to create a project using React, TypeScript, and Unsplash API. Basically, I'm trying to create an app to search for images, but my code is returning an empty array. What's wrong with my code?
ContextApi file
import axios from "axios"
import { createContext, ReactNode, useEffect, useState } from "react"
interface Image {
id: string
urls: {
regular: string
}
}
interface SearchContextProps {
searchImage: string
setSearchImage: (searchImage: string) => void
images: Image[]
setImages: (images: Image[]) => void
fetchData: (query?: string) => Promise<void>
}
export const ImageContext = createContext({} as SearchContextProps)
interface SearchContextProviderProps {
children: ReactNode
}
function ImageSearchProvider({ children }: SearchContextProviderProps) {
const [searchImage, setSearchImage] = useState("")
const [images, setImages] = useState<Image[]>([])
async function fetchData(query?: string) {
const response = await axios.get(
`https://api.unsplash.com/search/photos?per_page=30&query=${
query || searchImage
}&client_id=${import.meta.env.VITE_UNSPLASH_API_KEY}`
)
setImages(response.data.results)
}
useEffect(() => {
fetchData()
}, [])
return (
<ImageContext.Provider
value={{
searchImage,
setSearchImage,
images,
setImages,
fetchData,
}}
>
{children}
</ImageContext.Provider>
)
}
export default ImageSearchProvider
This is the Gallery component. The console.log(images)
is returning an empty array and I don't know why.
import { useContext } from "react"
import { ImageContext } from "../../contexts/ImageContext"
import { GalleryContainer, Img } from "./styles"
interface Image {
id: string
urls: {
regular: string
}
}
function Gallery() {
const { images } = useContext(ImageContext)
console.log(images)
return (
<GalleryContainer>
{images.map((image: Image) => {
return <Img key={image.id} src={image.urls.regular} />
})}
</GalleryContainer>
)
}
export default Gallery