Trying to practice api but I'm stuck trying to import the recipe template. The form shows but nothing else. The console also shows no errors. Any help would be appreciated.
Here is the App.js
import React, { useEffect, useState } from "react";
import Recipe from "./Recipe.js";
function App() {
let [recipes, setRecipes] = useState([]);
useEffect(() => {
getRecipes();
}, []);
const getRecipes = async () => {
const response = await fetch(
`///url///`
);
const data = await response.json();
setRecipes = data.hits;
console.log(data.hits);
};
return (
<div className="App">
<form className="search-form">
<input type="text" className="search-bar" />
<button type="submit" className="search-button">
Search
</button>
</form>
{recipes.map(recipe => (
<Recipe />
))}
</div>
);
}
export default App;
Here is Recipe.js
const Recipe = () => {
return (
<div>
<h1>Title</h1>
<p>Calories</p>
</div>
);
};
export default Recipe;
You're not updating the recipes state inside the getRecipes function correctly. You should call the setRecipes state updater function with the new state.
setRecipes = data.hits;
should be
setRecipes(data.hits)
Related
So I want to toggle between different categories in my react movie-app such as Trending,Top Rated,Popular etc.I am use useState hook for this,by making the initial state as one category then changing the state through the onClick event on the buttons.But it doesn't seem to be working.What could be the problem?
Code:
App.js
import { useState } from "react";
import Movie from "./components/Movie";
import requests from "./components/ApiRequest";
import Navbar from "./components/Navbar";
function App() {
const [category, setCategory] = useState('top_rated')
return (
<div className="App">
<Navbar setCategory={setCategory} />
<div className="movie-container">
<Movie fetchUrl={"movie/" + category + "?api_key=" + API_KEY + "&language=en-US&page=1"} />
</div>
</div>
);
}
export default App;
Navbar.js
import React from 'react'
import SearchBar from './SearchBar'
import { FiFilter } from 'react-icons/fi'
const Navbar = ({ setCategory }) => {
return (
<div className="navbar-container">
<button className="navbar-btn"><FiFilter />Filter</button>
<div className="categories">
<button className="cat-btn" onClick={() => setCategory("popular")}>Popular</button>
<button className="cat-btn" onClick={() => setCategory("top_rated")}>Top Rated</button>
<button className="cat-btn" onClick={() => setCategory("upcoming")}>Upcoming</button>
</div>
<SearchBar />
</div>
)
}
export default Navbar
Movie.js
const Movie = ({ fetchUrl }) => {
const [movie, setMovie] = useState([]);
useEffect(() => {
async function getPost() {
const response = await client.get(fetchUrl);
console.log(response);
setMovie(response.data.results);
// return response;
}
getPost();
}, [])
return (
movie.map((m) => (
<div className="movie-component" key={m.id}>
<img src={`https://image.tmdb.org/t/p/w500${m.backdrop_path}`} alt="" />
<div className="metadata">
<h1>{m.title}</h1>
<a>⭐{m.vote_average}</a>
</div>
</div>
)
))
}
So I have initialized the useState hook in App.js and then using it in Navbar.js as the set the state of this hook on click event.
useEffect(() => {
async function getPost() {
const response = await client.get(fetchUrl);
console.log(response);
setMovie(response.data.results);
// return response;
}
getPost();
}, [fetchURL])
please update your dependency array as follows.
on changing the category, fetchURL value is being changed.
so it need to be included in dependency array of useEffect Hook.
I tried to make new component for list film. But it seems error in page Home.
Here my code in component list map:
import './Home.css';
import './ListFilm';
import ListFilm from './ListFilm';
function Home() {
return (
<div className="Home">
<h2>The List of Films</h2>
<div className="list film">
<ListFilm/>
</div>
</div>
);
}
export default Home;
Here is component file named ListFilm.js :
import {useState, useEffect} from 'react';
function ListFilm() {
const [post, setPost] = useState({});
useEffect(() => {
const fetchData = async () => {
const response = await fetch(
"https://api.themoviedb.org/3/movie/now_playing?api_key=9e0de5499870264659308848dbad6b2a"
);
const data = await response.json();
setPost(data);
console.log(response)
console.log(data);
};
fetchData();
}, []);
return (
<>
{post.results && post.results.map((item, index) => (
<div key={index}>
<h3>{item.original_title}</h3>
<img src={item.backdrop_path} alt="poster"/>
<p>Tanggal Rilis: {item.release_date}</p>
</div>
))}
</>
);
}
export default ListFilm;
The goal is making data and image in listfilm.js showing in page Home.js. The error code in console log said that index.js:1 The above error occurred in the component: Please help me. Thanks
I am using useEffect to hit an api and display some data from the response.It works well in console but when i try to display the data in a component it throws an error.I am checking for the loading state though.I am showing the data after a i get a response then where does this null coming from
App.js file:
import { useState, useEffect } from 'react';
import Details from './components/Details/Details';
import Header from './components/Header/Header';
import GlobalStyle from './globalStyles';
const API_KEY = 'Private';
// const URL = `https://geo.ipify.org/api/v1?apiKey=${API_KEY}&ipAddress=${ip}`;
function App() {
const [ip, setIp] = useState('8.8.8.8');
const [response, setResponse] = useState(null);
const [error, setError] = useState(null);
const [isLoading, setIsLoading] = useState(false);
useEffect(() => {
const fetchData = async () => {
setIsLoading(true);
try {
const res = await fetch(
`https://geo.ipify.org/api/v1?apiKey=${API_KEY}&ipAddress=${ip}`
);
const json = await res.json();
setResponse(json);
setIsLoading(false);
} catch (error) {
setError(error);
}
};
fetchData();
// return { response, error, isLoading };
}, [ip]);
return (
<>
<GlobalStyle />
<Header getIp={(q) => setIp(q)} />
<Details isLoading={isLoading} res={response} error={error} />
</>
);
}
export default App;
Header.js file:
import { useState } from 'react';
import { FaArrowRight } from 'react-icons/fa';
import React from 'react';
import { Form, FormInput, Head, HeadLine, Button } from './Header.elements';
// import { useFetch } from '../../useFetch';
const Header = ({ getIp }) => {
const [input, setInput] = useState('');
const onChange = (q) => {
setInput(q);
getIp(q);
};
return (
<>
{/* styled components */}
<Head>
<HeadLine>IP Address Tracker</HeadLine>
<Form
onSubmit={(e) => {
e.preventDefault();
onChange(input);
setInput('');
}}
>
<FormInput
value={input}
onChange={(e) => {
setInput(e.target.value);
}}
placeholder='Search for any IP address or Domain'
/>
<Button type='submit'>
<FaArrowRight />
</Button>
</Form>
</Head>
</>
);
};
export default Header;
Details.js file:
import React from 'react';
import { Box, Location } from './Details.elements';
const Details = ({ res, error, isLoading }) => {
console.log(res);
return isLoading ? (
<div>loading...</div>
) : (
<>
<Box>
<Location>{res.location.city}</Location>
</Box>
</>
);
};
export default Details;
the error it shows:
That happens because on the first render, Details component will receive isLoading=false and res=null, so it will try to render the box so it's throwing the error.
You can initialize isLoading as true.
const [isLoading, setIsLoading] = useState(true);
Or render the Location if res has some value.
<Box>
{res && <Location>{res.location.city}</Location>}
</Box>
According to React documentation :
https://reactjs.org/docs/hooks-reference.html
By default, effects run after every completed render, but you can
choose to fire them only when certain values have changed.
So your component is rendering at least once with isLoading as false before even the API call starts.
You have two choices here:
Set isLoading initial value to true
Add optional chaining res?.location.city
https://codesandbox.io/s/stackoverflow-67755606-uuhqk
Hi guys trying to make an mini application in react JS , in that application i want to display data in the my body part when i do search on my textbar , so anyone tell me how can i do it or what should i do to display data?
App.js This is my main component
import './App.css';
import Star from './Star';
import People from './People';
import Planet from './Planet';
function App(props) {
const {people,planet} = props;
return (
<div className="App">
<Star />
<People data={people}/>
<Planet data={planet}/>
</div>
);
}
export default App;
Star.js
This is my star component where i fetch my all star war apis
import React, { useState, useEffect } from 'react';
import './Star.css';
const Star = () => {
const [search, setSearch] = useState('');
const [people, setPeople] = useState([]);
const [planet, setPlanet] = useState([]);
const onSubmit = (e) => {
e.preventDefault();
if (search === "") {
alert("please Enter some value");
}
}
useEffect(() => {
async function fetchPeople() {
let result = await fetch("https://swapi.dev/api/people/?format=json");
let data = await result.json();
setPeople(data.results);
}
async function fetchPlanet() {
let result = await fetch("https://swapi.dev/api/planets/?format=json");
let data = await result.json();
setPlanet(data.results);
}
fetchPeople();
fetchPlanet();
}, [])
console.log("people", people);
console.log("planet", planet);
return (
<div>
<div className='container'>
<h2>Star War</h2>
<div className='jumbotron'>
<input type="text"
className="form-control"
placeholder='Search...'
value={search}
onChange={(e) => setSearch(e.target.value)} />
<span><button className='btn btn-secondary' onClick={onSubmit}>Search</button></span>
</div>
</div>
</div>
)
}
export default Star;
people.js
This is my people that i want to display in the my body part
import React from 'react';
const People = (props) => {
const { data } = props;
return (
<div className="row">
{data && data.map((people, i) => {
return (
<div className="col-md-3" key={i}>
<div className="card">
<div className="card-body">
<h4>{people.name}</h4>
</div>
</div>
</div>
)
})}
</div>
);
};
export default People;
If I understand correctly your issue, you want to display the People component and the issue is how to pass it the data fetched in the Star component.
The solution is to move the state of the data in the parent component so that it can be passed easily to all its children.
function App(props) {
const [people, setPeople] = useState([]);
const [planet, setPlanet] = useState([]);
useEffect(() => {
async function fetchPeople() {
let result = await fetch("https://swapi.dev/api/people/?format=json");
let data = await result.json();
setPeople(data.results);
}
async function fetchPlanet() {
let result = await fetch("https://swapi.dev/api/planets/?format=json");
let data = await result.json();
setPlanet(data.results);
}
fetchPeople();
fetchPlanet();
}, [])
return (
<div className="App">
<Star
people={people} //if you need these in the Star component
planet={planet} //if you need these in the Star component
/>
<People data={people}/>
<Planet data={planet}/>
</div>
);
}
I have a question on React Hooks. This is a sample of my code :-
import React, { useState, useEffect } from "react";
import Card from "./Card";
const CardsBoard = () => {
useEffect(() => {
doRatingClickProcessing()
}, [ratingObj])
const doRatingClickProcessing = () => {
const { player, title, rating } = ratingObj
}
return (
<div className="container-fluid justify-content-center">
<div className="row">
<div className="col-md-6">
<Card
cardInfo={player1Card}
player={1}
showCard={visiblePl1}
clickableRatings = {clickableRatings}
onClick={ratingObj => setRatingObj(ratingObj)}
/>
</div>
<div className="col-md-6">
<Card
cardInfo={player2Card}
player={2}
showCard={visiblePl2}
clickableRatings = {clickableRatings}
onClick={ratingObj => setRatingObj(ratingObj)}
/>
</div>
</div>
)}
</div>
)
}
export default CardsBoard
Then in the card component I am returning the ratingObj successfully when the user clicks on a rating.
In the Card Component I have something like this:-
<div
className="col-md-2 text-left card-rating-color"
onClick={() =>
onClick({
player: player,
title: row[0].title,
rating: row[0].rating,
})
}
>
{row[0].rating}
</div>
However I am puzzled why useEffect() is triggered even when the Card component is loaded, and ratingObj is still empty. Shouldn't it be triggered only if the ratingObj is filled up?
Thanks for your help and time
useEffect will call at least once. it doesn't matter either your object is updating or not because when you write
useEffect(()=>{
},[ratingObj]);
In above code you are passing object into square brackets right. That means you are mentioning dependencies as e second parameter and empty [] in argument list will call once at least. After that, it depends on ratingObj that you have passed in.
import React, {useState,useMemo} from 'react';
const App = () => {
const [name, setName] = useState('');
const [modifiedName, setModifiedName] = useState('');
const handleOnChange = (event) => {
setName(event.target.value);
}
const handleSubmit = () => {
setModifiedName(name);
}
const titleName = useMemo(()=>{
console.log('hola');
return `${modifiedName} is a Software Engineer`;
},[modifiedName]);
return (
<div>
<input type="text" value={name} onChange={handleOnChange} />
<button type="button" onClick={handleSubmit}>Submit</button>
<Title name={titleName} />
</div>
);
};
export default App;
const Title = ({name}) => {
return <h1>{name}</h1>
}