Estoy haciendo una aplicación que renderiza Gifs (de la API de Giphy) con React y TypeScript y me está dando un problema al externalizar el servicio a un fichero externo para dejar el código más limpio. Veamos los siguientes componentes de mi aplicación.
GifGridItem.tsx
(simplemente te devuelve cada Gif ya para mostrar en la app):
import React, { useState } from "react";
import { GifsInterface } from "./GifGrid";
import "../index.css";
function GifGridItem(props: GifsInterface) {
const { id, title, url } = props;
return (
<div className="card">
<img src={url} alt={title} />
<p>{title}</p>
</div>
);
}
export default GifGridItem;
GifGrid.tsx
(te renderiza el listado de gifs):
import React, { useState, useEffect } from "react";
import GifGridItem from "./GifGridItem";
import "../index.css";
import { getGifs } from "../helpers/getGifs";
export interface GifGridProps {
information: string;
}
export interface GifsInterface {
id?: string;
title?: string;
url?: string;
}
function GifGrid(props: GifGridProps): JSX.Element {
const { information } = props;
const [images, setImages] = useState<GifsInterface[]>([]);
useEffect(() => {
getGifs(information).then(setImages);
}, []);
return (
<>
<h3>{information}</h3>
<div className="card-grid">
{images.map((img) => (
<GifGridItem key={img.id} title={img.title} url={img.url} />
))}
</div>
</>
);
}
export default GifGrid;
GetGifs.tsx
(fichero dónde te hago la llamada a la API).
import { GifGridProps } from "../components/GifGrid";
export const getGifs = async (props: GifGridProps) => {
const { information } = props;
const url = `https://api.giphy.com/v1/gifs/search?api_key=${api_key}&q=${encodeURI(
information
)}&limit=10`;
const resp = await fetch(url);
const { data } = await resp.json();
const gifs = data.map((img: any) => {
return {
id: img.id,
title: img.title,
url: img.images?.downsized_medium.url,
};
});
return gifs;
};
También tengo el componente AddCategory.tsx
, que te permite añadir una nueva keyword para que la lógica de la app te acabe llamando a la API usando esa keyword.
import React, { useState } from "react";
import { InformationProps } from "../interfaces";
function AddCategory({ setInformation }: InformationProps) {
const [inputValue, setInputValue] = useState<string>("");
const handleInputChange = (e: any) => {
setInputValue(e.target.value);
};
const handleSubmit = (e: any) => {
e.preventDefault(); //It avoids the page to load again when the form is submitted
if (inputValue.trim().length > 2) {
//In order to avoid insert elements without text
setInformation((information: string[]) => [inputValue, ...information]);
setInputValue(" "); //Cleaning the textbar
}
};
return (
<form onSubmit={handleSubmit}>
<input
type="text"
onChange={handleInputChange}
className="textBar"
value={inputValue}
/>
</form>
);
}
export default AddCategory;
Y por último tengo GifExpertApp.tsx
:
import React, { useState } from "react";
import AddCategory from "./components/AddCategory";
import GifGrid from "./components/GifGrid";
function GifExpertApp() {
const [information, setInformation] = useState<string[]>([""]);
return (
<div className="App">
<header className="App-header">
<h1>Gif Expert App</h1>
<AddCategory setInformation={setInformation} />
<hr />
<ol>
{information.map((information) => {
return <GifGrid key={information} information={information} />;
})}
</ol>
</header>
</div>
);
}
export default GifExpertApp;
He compartido todo el código porque no sé debido al envío de las props con TypeScript hasta que punto era importante compartir todo el código. En resumen, mi problema está en que en el archivo GifGrid.tsx
, en este trocito de código:
useEffect(() => {
getGifs(information).then(setImages);
}, []);
me marca error en information
, ya que me dice que Argument of type 'string' is not assignable to parameter of type 'GifGridProps'
. Sin embargo, no lo comprendo, ya que precisamente esa interfaz sólo tiene una variable que es information
y que, precisamente, es de tipo String
. ¿Alguien me podría indicar en qué estoy fallando? Muchas gracias :)