I am a beginner and I could fetch and display API data object with map() function. Now I am trying to create a global fetch button and call the data with onClick that I fetched. When I check onClick with console.log, it works, but for some reason I can't display it in browser and it gives me no error.
App component
import React, {useState, useEffect} from 'react';
import Recipe from "./Recipe";
import Style from "./style.css"
export default function App() {
const [data, setData] = useState([]);
const [search, setSearch] = useState("");
const [myFilter, setFilter] = useState("chicken");
const recipeApi = {/*recipe api address*/}
const fetchData = () => {
fetch(recipeApi)
.then(res => res.json())
.then(result => setData(result.hits))
.catch(err => console.log("error"))
}
useEffect(() => {
fetchData()
}, [myFilter])
const searching = event => {
setSearch(event.target.value)
}
const mySearch = event => {
event.preventDefault();
setFilter(search);
setSearch("");
}
function deleteHandler(index){
setData(
data.filter((element, filterIndex) => index !== filterIndex)
)
}
console.log(fetchData)
return (
<div className="App">
<button type="submit" onClick = {fetchData}>fetch</button>
<form onSubmit = {mySearch} className = "search-form">
<input className = "search-bar" value = {search} onChange = {searching} />
<button className ="search-button" type="submit">search</button>
</form>
<button type="submit" onClick = {fetchData}>search</button> {/*here I call my fetched data */}
<div className = "recipes"
{data.map((element, index)=>(
<Recipe
onDelete={deleteHandler}
title = {element.recipe.label}
image = {element.recipe.image}
name = {element.recipe.source}
index={index}
key = {index}
calories = {element.recipe.calories}
ingredientLines = {element.recipe.ingredientLines[0]}
/>
))
}
</div>
</div>
);
}
child component
import React from "react";
import style from "./recipe.module.css"
export default function Recipe({title, image, name, calories, index, onDelete,refetch, ingredientLines}){
return (
<div className = {style.recipe}>
<h3>{title}</h3>
<p>{name}</p>
<p>Calories: {calories}</p>
<p>Ingredients: {ingredientLines}</p>
<img className = {style.image} src = {image} alt="" />
<button type="button" onClick={() => onDelete(index)} className="btn btn-danger">Delete</button>
</div>
)
}
console.log(fetchData)toconsole.log(data)to see if it looks right.