Reputation: 157
I have a simple site that fetches data from Spoonacular API and searches for ingredients, the response comes with a title and image. I have declared the types as:
export interface IProps {
id: number;
name: string;
image: string;
}
So far my list of ingredients looks like:
const List = (props: { ingredient: IProps }) => {
const { ingredient } = props;
return (
<Container>
<Box>
<Image src={ingredient.image} alt={ingredient.name} />
<Box>
{ingredient.name}
</Box>
</Box>
</Container>
);
};
export default List;
I have removed everything related to styling up here FYI.
The props come from where I make the call:
const Search = () => {
const [ingredients, setIngredients] = useState<IProps[]>([]);
const [value, setValue] = useState("");
const handleSubmit = (e) => {
e.preventDefault();
axios
.get(
`https://api.spoonacular.com/food/ingredients/search?query=${value}&number=2&apiKey=${URL}`
)
.then((res) => res.data)
.then((data) => data.results)
.then((data) => setData(data))
.catch((err) => console.log(err));
};
const handleChange = (e) => {
setValue(e.target.value);
};
return (
<Flex justifyContent="center">
<Flex direction="column">
<Heading mb={6}>Search Recipe</Heading>
<Input
onChange={handleChange}
value={value}
name="search"
id="search"
placeholder="Write here..."
variant="filled"
mb={2}
type="text"
/>
<Button onClick={handleSubmit} mb={5}>
Search
</Button>
</Flex>
{ingredients.map((ingredient) => (
<List key={ingredient.id} ingredient={ingredient} />
))}
</Flex>
);
};
export default Search;
But what I don’t get is the fact that I get a 404 from the image:
Request URL: http://localhost:3000/lemon.png
Request Method: GET
Status Code: 404 Not Found
Remote Address: 000.0.0.0:0000
Referrer Policy: strict-origin-when-cross-origin
Since I am new with typescript, I might have missed something quite basic?
Upvotes: 0
Views: 1259
Reputation: 93
Adding to what Ritik Mishra has said, and just as an example for you and other people using Spoonacular, your src would look like:
src={`https://spoonacular.com/cdn/ingredients_250x250/${ingredient.image}`}
Upvotes: 2
Reputation: 718
What is happening is that the API is only giving you a filename like lemon.png
. To locate the image from the API, you need to append it to the string https://spoonacular.com/cdn/ingredients_100x100/
before passing it into the Image
component i.e in this case, you would end up with https://spoonacular.com/cdn/ingredients_100x100/lemon.png
.
You can find more information about getting images from the API here (link to Spoonacular API docs)
Upvotes: 3