React.useEffect(() => {
if (inputRef.current) {
inputRef.current.focus();
}
const data = localStorage.getItem("todos");
}, []);
useEffect(() => {
localStorage.setItem("todos", JSON.stringify(todos));
}, [todos]);
const [state, setState] = React.useState()
function App() {
const [search, setSearch] = React.useState("");
const [query, setQuery] = React.useState<string>("steak");
const [recipes, setRecipes] = React.useState<Welcome["hits"]>([]);
async function fetchApi() {
try {
const response = await axios.get<Welcome>(
`https://api.edamam.com/search?q=${query}&app_id=${ID}&app_key=${KEY}`
);
setRecipes(response.data.hits);
} catch (e: unknown) {
console.warn(e);
}
}
console.log(recipes);
React.useEffect(() => {
fetchApi();
}, [query]);
const gainSearch = (event: React.FormEvent) => {
event.preventDefault();
setQuery(search);
setSearch("");
};
const updateSearch = (event: any) => {
setSearch(event.target.value);
};
return (
<div className="App">
{recipes.map((recipe) => {
<h2>{recipe.recipe.calories}</h2>; //не отображается
})}
</div>
);
}
export default App;
const recipes: Hit[]
Type 'void[]' is not assignable to type 'ReactNode'.
Type 'void[]' is not assignable to type 'ReactFragment'.
The types returned by '[Symbol.iterator]().next(...)' are incompatible between these types.
Type 'IteratorResult' is not assignable to type 'IteratorResult'.
Type 'IteratorYieldResult' is not assignable to type 'IteratorResult'.
Type 'IteratorYieldResult' is not assignable to type 'IteratorYieldResult'.
Type 'void' is not assignable to type 'ReactNode'.
<div className="App">
{recipes.map((recipe): any => {
<h2>{recipe.recipe.calories}</h2>;
})}
</div>
<div className="App">
{recipes.map((recipe) => {
<Recipe
key={recipe.recipe.label}
image={recipe.recipe.image}
calories={recipe.recipe.calories}
ingredients={recipe.recipe.ingredients}
/>;
})}
</div>
import React from "react";
interface IProps {
label: string;
image: string;
calories: number;
ingredients: Array<any>;
}
export default function Recipe({
label,
image,
calories,
ingredients,
}: IProps) {
return <h1>{calories}</h1>;
}
<div class="test">TEST</div>
<div class="test">TEST</div>
<div class="test">TEST</div>
const test = document.querySelectorAll('.test');
test.forEach((element) => {
element.style.color = "red"
})
function App() {
const [search, setSearch] = React.useState("");
const [query, setQuery] = React.useState<string>("steak");
const [recipes, setRecipes] = React.useState<Welcome["hits"]>([]);
async function fetchApi() {
try {
const response = await axios.get<Welcome>(
`https://api.edamam.com/search?q=${query}&app_id=${ID}&app_key=${KEY}`
);
setRecipes(response.data.hits);
} catch (e: unknown) {
console.warn(e);
}
}
console.log(recipes);
React.useEffect(() => {
fetchApi();
}, [query]);
const gainSearch = (event: React.FormEvent) => {
event.preventDefault();
setQuery(search);
setSearch("");
};
const updateSearch = (event: any) => {
setSearch(event.target.value);
};
return (
<div className="App">
{recipes.map((recipe) => (
<Recipe
key={recipe.recipe.label}
title={recipe.recipe.label}
image={recipe.recipe.image}
calories={recipe.recipe.calories}
ingredients={recipe.recipe.ingredients}
/>
))}
</div>
);
}
(property) title: any
Type '{ key: any; title: any; image: any; calories: any; ingredients: any; }' is not assignable to type 'IntrinsicAttributes'.
Property 'title' does not exist on type 'IntrinsicAttributes'.
const [recipes, setRecipes] = React.useState<Welcome["hits"]>([]);
const fetchApi = () => {
try {
fetch(
`https://api.edamam.com/search?q=${query}&app_id=${ID}&app_key=${KEY}`
)
.then((res) => res.json())
.then((data) => setRecipes(data.hits));
} catch (e) {
console.log(e);
}
};
console.log(recipes);
hitsкоторый состоит из нескольких обьектов но я не могу по-нему пробежаться мапом..
const [recipes, setRecipes] = React.useState<Welcome["hits"]>([]);
async function fetchApi() {
try {
const response = await axios.get<Welcome["hits"]>(
`https://api.edamam.com/search?q=${query}&app_id=${ID}&app_key=${KEY}`
);
setRecipes(response.data); //hits не дает записать, <blockquote>Property 'hits' does not exist on type 'Hit[]'</blockquote>
console.log(recipes);
} catch (e: unknown) {
console.warn(e);
}
}
только если ты сам напишешь вот так await axios.get.... Т.е. ты прямым текстом говоришь typescript'у, что в ответе сервера ждёшь МАССИВ Ingredient[], а не объект, имеющий поле hits, а потом удивляешься, что он тебе об этом прямо говорит.- выходит что моя новая запись
const [recipes, setRecipes] = React.useState<Welcome["hits"]>([]);
const response = await axios.get<Welcome["hits"]>(
`https://api.edamam.com/search?q=${query}&app_id=${ID}&app_key=${KEY}`
);
тоже неверная тк как я тут тоже ожидаю массив а должен ожидать обьект. Смотрел документацию и некоторые туториалы и там получение данных происходит примерно так же как я и написал. Может дело в типах ?
Если ты хочешь положить в setRecipes массив hits, то и клади туда, блин, массив hits: setRecipes(response.data.hits).
setRecipes(response.data.hits).
то сразу же получаю ошибку Property 'hits' does not exist on type 'Ingredient[]', подставлял абсолютно все интерфейсы и везде одни и та же ошибка.
const[recipes, setRecipes] = React.useState<Welcome>([]);
Argument of type 'never[]' is not assignable to parameter of type 'Welcome | (() => Welcome)'
const[recipes, setRecipes] = React.useState<Welcome[]>([]);
async function fetchApi(){
try{
const response = await axios.get<Welcome[]>(`https://api.edamam.com/search?q=${query}&app_id=${ID}&app_key=${KEY}`);
setRecipes(response.data);
console.log(recipes)
}catch(e: unknown){
console.warn(e);
}
}
const[recipes, setRecipes] = React.useState<Irecipe[]>([]);
async function fetchApi(){
try{
const response = await axios.get<Irecipe[]>(`https://api.edamam.com/search?q=${query}&app_id=${ID}&app_key=${KEY}`);
setRecipes(response.data);
console.log(recipes)
}catch(e: unknown){
console.warn(e);
}
}
setRecipes(response.hits);
setRecipes(response.data);
const[recipes, setRecipes] = React.useState<Welcome>();
async function fetchApi(){
try{
const response = await axios.get<Welcome>(`https://api.edamam.com/search?q=${query}&app_id=${ID}&app_key=${KEY}`);
setRecipes(response.data);
console.log(recipes?.hits[0].recipe.calories) //Тут данные с обьекта выводятся
}catch(e: unknown){
console.warn(e);
}
}
React.useEffect(()=> {
fetchApi()
}, [query]);
const gainSearch = (event: React.FormEvent) => {
event.preventDefault();
setQuery(search);
setSearch('');
}
const updateSearch = (event: any)=>{
setSearch(event.target.value);
}
return (
<div className="App">
{recipes.map((recipe:Welcome) => {
<Recipe key={recipe.hits}/> //Здесь уже получаю ошибку <blockquote>Object is possibly 'undefined'.</blockquote>
})}
</div>
);
}
export default App;