I am using Nextjs and trying to fetsch the edamam api. I have a search input field to search using Axios. Not sure why am I getting the error. AxiosError {message: 'Request failed with status code 400', name: 'AxiosError', code: 'ERR_BAD_REQUEST', config: {…}, request: XMLHttpRequest, …} code : "ERR_BAD_REQUEST" config : {transitional: {…}, adapter: Array(3), transformRequest: Array(1), transformResponse: Array(1), timeout: 0, …} message : "Request failed with status code 400" name : "AxiosError"
api.ts
import axios from 'axios';
const API_URL = 'https://api.edamam.com/api/recipes/v2';
const APP_ID = process.env.NEXT_PUBLIC_APP_ID;
const APP_KEY = process.env.NEXT_PUBLIC_APP_KEY;
interface Recipe {
recipe: {
uri: string;
label: string;
image: string;
ingredientLines: string[];
};
}
export const fetchRecipes = async (query: string): Promise<Recipe[]> => {
try {
const response = await axios.get(API_URL, {
params: {
q: query,
app_id: APP_ID,
app_key: APP_KEY,
},
});
return response.data.hits;
} catch (error) {
console.error('Error fetching recipes:', error);
return [];
}
};
Have .env.local file set up with the relevant id and key.
searchBar.tsx
// /components/SearchBar.tsx
import React, { useState } from 'react';
interface SearchBarProps {
onSearch: (query: string) => void;
}
const SearchBar: React.FC<SearchBarProps> = ({ onSearch }) => {
const [query, setQuery] = useState('');
const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
onSearch(query);
};
return (
<form onSubmit={handleSubmit}>
<input
type="text"
value={query}
onChange={(e) => setQuery(e.target.value)}
placeholder="Search for recipes..."
/>
<button type="submit">Search</button>
</form>
);
};
export default SearchBar;
also have
<Item>
<SearchBar onSearch={handleSearch} />
<RecipeList recipes={recipes} />
</Item>
The documentation for the API lists the type
parameter as "required", but is not part of your request.
const response = await axios.get(API_URL, {
params: {
type: 'public',
q: query,
app_id: APP_ID,
app_key: APP_KEY,
}
});