Making List of Map from Other Component Show in HTML - javascript

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

Related

React infinite scroll in an Unsplash image app

I am building an image search app using Unsplash API and trying to implement react infinite scroll (https://www.npmjs.com/package/react-infinite-scroll-component), but it is not working properly.
Now, the search form works fine and it displays 10 images(which is the default number of images using Unsplash API) when you search something, but when I scroll down to the end of of the page, it only displays the loader (h4 'Loading') but it does not display more images.
App.js
import './App.css';
import Main from './components/Main';
function App() {
return (
<div className="App">
<Main />
</div>
);
}
export default App;
Main.js
import React from 'react'
import Header from './Header'
import Image from './Image'
import { useState, useEffect } from 'react'
import InfiniteScroll from 'react-infinite-scroll-component';
function Main() {
const [input, setInput] = useState('')
const [allImages, setAllImages] = useState([])
const [favorites, setFavorites] = useState(() => JSON.parse(localStorage.getItem("favorites")) || [])
useEffect(() => {
localStorage.setItem("favorites", JSON.stringify(favorites))
console.log(favorites)
}, [favorites])
function handleChange(event) {
setInput(event.target.value)
}
async function fetchImages() {
try {
const res = await fetch(`https://api.unsplash.com/search/photos?&query=${input}&client_id=${process.env.REACT_APP_UNSPLASH_API_KEY}`)
const data = await res.json();
setAllImages(data.results)
} catch(error) {
alert("Sum ting wong");
}
}
const handleSubmit = async (event) => {
event.preventDefault();
fetchImages()
}
console.log(`allImages: ${allImages.length}`);
// use parameter 'id' to read specific one
function isLiked(id) {
return favorites.find(el => el.id === id) ? true : false
}
return (
<main>
<Header
input={input}
handleChange={handleChange}
handleSubmit={handleSubmit}
/>
<InfiniteScroll
dataLength={allImages.length} //This is important field to render the next data
next={fetchImages}
hasMore={true}
loader={<h4>Loading...</h4>}
>
<div className='main--image-list mt-5 pb-5'>
{allImages.map(el => (
<Image
key={el.id}
// do need spread operator below for img's src to work in Image.js
{...el}
el={el}
isLiked={isLiked(el.id)}
favorites={favorites}
setFavorites={setFavorites}
/>
))}
</div>
</InfiniteScroll>
</main>
)
}
export default Main
for visuals

React JS API item.map

import React, { useState, useEffect, } from "react";
function ProductDetail({match}) {
useEffect(() => {
fetchItem();
// console.log(match)
}, );
const fetchItem = async () => {
const fetchItem = await fetch(`https://fortnite-api.theapinetwork.com/item/get?id={{itemid}}`);
const item = await fetchItem.json();
console.log(item);
}
return (
<div className="containter productsDetails">
<h1>Product Detail</h1>
</div>
);
}
export default ProductDetail;
enter image description here
import React, { useState, useEffect } from "react";
import {Link} from "react-router-dom";
function Products() {
const [data, setData] = useState([]);
const apiGet = () => {
fetch(`https://fortnite-api.theapinetwork.com/items/popular`)
.then((response) => response.json())
.then((json) => {
console.log(json);
setData(json);
});
};
useEffect(() => {
apiGet();
},[])
return (
<div>
<div>
<ul>
{data.map(item =>
<li key={item.id}>
<Link to={`/products/${item.id}`}>{item.item}</Link>
</li>
)}
</ul>
</div>
</div>
);
}
export default Products;
I have tried every way I can find online.
I am unable to map into the entries object of this API. I would like to map to the 3 array objects.
So that I can {match} using an ID when I click one of them.
The routing is working. But I can not display any of the data on the screen. In Console it is displaying.
He is the API fortnite-api.theapinetwork.com/items/popular
You're trying to use map function on object. map only works for arrays.
Here's the link to sandbox how it should be

Not able to change the state on clicking between different categories in moviedb-app

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.

React not importing file. Console shows no errors

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)

React, Adding data from json to single post component

I try to write website in React and that was going fine until now. I totally got stuck.
I have component with list of posts which is working fine. My problem is, that I dont know how to add data from JSON to single post component. I was trying to change geting my JSON data from list articles component to app.js and then passing it down to component with my list posts and to single post component, but then I have error with map() function.
//geting data from JSON and passing it through props down
import React, { useEffect, useState } from "react";
import "./style.css";
import SideBar from "../SideBar";
import MainContent from "../MainContent";
import blogData from "../../assets/data/blog.json";
const MainContainer = () => {
const [posts, setPosts] = useState([]);
useEffect(() => {
const post = blogData.data;
setPosts(post);
}, []);
return (
<div className="main-container">
<MainContent posts={posts} />
<SideBar posts={posts} />
</div>
);
};
export default MainContainer;
//mapping through posts
import React from "react";
import "./style.css";
import Post from "../Post";
const MainContent = ({ posts }) => {
return (
<main className="main-content">
{posts.map(post => {
return <Post key={post.id} post={post} />;
})}
</main>
);
};
export default MainContent;
//Post from list of posts
const Post = ({ post }) => {
return (
<div className="post">
<Animated
animationIn="bounceInLeft"
animationOut="fadeOut"
isVisible={true}
>
<h3 className="postTitle">{post.blogTitle}</h3>
<div className="imgContainer">
<img
alt="travel"
src={require("../../assets/img/" + post.blogImage)}
></img>
</div>
<p className="postDescription">{post.blogText}</p>
<NavLink to={`/post/${post.id}`}>
<h5 className="postLink">Read more</h5>
</NavLink>
<h5 className="posteDate">
Posted on {post.postedOn} by {post.author}
</h5>
</Animated>
</div>
);
};
export default Post;
Here is link to my repo:
https://github.com/Gitarrra92/travel-blog/
I think I should have a state in my component with single object of specific id. I just still dont know how to do this. This is my SinglePost component
const SinglePost = ({ match }) => {
const [singlePosts, setSinglePost] = useState({});
useEffect(() => {
const singlePost = blogSingleData.data;
setSinglePost(singlePost);
console.log(singlePost);
}, [match]);
return (
<>
<Socials />
</>
);
};
export default SinglePost;

Categories