Fetching the constant value from a component in react to another page - reactjs

I have a component NFTCard as below, that displays images as card
import React, {useCallback, useState} from "react";
const NFTCard = ({nft}) => {
const [image, setImage] = useState(null);
const handleImage = useCallback(event => {
setImage(event.target.src)
console.log(event.target.src)
console.log(image)
},[image])
return(
//Wrapping the image in a card
<div className="rounded overflow-hidden shadow-lg">
<img className= "object-contain h-50 w-50"
src={nft.meta.image.url.ORIGINAL}
alt={nft.meta.name}
onClick= {handleImage}
/>
<div className="px-1 py-1">
<div className="font-bold text-xs mb-0">{nft.meta.name}</div>
</div>
</div>
)
}
export default NFTCard
What I am trying to do here is whenever an image on a card is clicked, I wish to display it again as an enlarged form in another div element
Here is my main page where i am displaying the image
import Link from 'next/link';
import { useWeb3Context } from '../../context'
import { Web3Address, Web3Button } from '../../components';
import React, { useEffect, useState } from 'react';
import NFTCard from '#/components/NFTCard';
import {useRouter} from 'next/router';
//render only the web3 button if the user is not connected to the web3 provider
const renderNotConnectedContainer = () => (
<div>
<p>Connect Wallet to continue</p>
</div>
);
export const ChooseProductView = () => {
const router = useRouter();
const { address } = useWeb3Context()
const [nfts, setNfts] = useState([]);
// Function to get the details of the NFTs held in the Wallet
const fetchNFTs = async () =>
{
const accounts = await window.ethereum.request({method: 'eth_requestAccounts'});
const response = await fetch(`https://ethereum-api.rarible.org/v0.1/nft/items/byOwner?owner=${accounts[0]}&size=100`)
//limiting the size to 100 so that there is not too much data to fetch
const data = await response.json()
setNfts(data.items)
console.log(data.items)
}
//creating a useEffect to fetch the NFTs details which is an async function
useEffect(() => {
const getNFTs = async () => {
await fetchNFTs()
}
getNFTs()
}, [])
if(!address){
return renderNotConnectedContainer()
}
else{
//rendering the NFTs details via the NFTContainer component
return(
<div className="flex flex-row">
<div className="basis-1/4"> {/*Splitting the screen into 3 parts*/}
<br/>
<div className = "container mx-auto">
<div className="grid grid-cols-2 gap-2 auto-rows-max">
{/*Calling the NFTCard component to render the NFTs details*/}
{nfts.map((nft, index) => {
return <NFTCard nft={nft} key= {index}/>
})
}
</div>
</div>
</div>
<div className="basis-1/2">
<div className="max-w-lg container mx-auto">
<img className="w-full" src={`${router.basePath}/assets/images/Hoodie black label.jpg`} alt="Empty Hoodie"/>
<div className="px-4 py-6">
</div>
</div>
</div>
<div className="basis-1/4">
<Web3Address/>
</div>
</div>
)
}
};
How do i fetch the image url stored in NFTCard with use state into a div element in ChooseProductView?
Thanks a lot in advance

Related

Send predetermined string into my video iframe youtbe player-React

I'm trying to make a FAQ of sorts, right now I have it as a search bar but I'm having a hard time sending a value that I want the videos to populate with. I want the user to have the option to click on the button, and that specific button have the data of "How to find a queen" and send that automaitcally to the iframe player. Any pointers on how to achieve this? As I have it right now, my handleSubmit populates the search bar.
SearchBar.jsx
import React, { useState } from 'react';
import "./SearchBar.css";
const SearchBar = (props) => {
const [searchRequest, setSearchRequest] = useState('');
const handleSubmit = (event) => {
event.preventDefault();
props.getSearchResults(searchRequest);
setSearchRequest('What Does a Queen Bee look like?');
}
return (
<div className='search-contain'>
<form className='search-form-contain' onSubmit={handleSubmit}>
<label className='search-label'>Search:</label>
<input type='text' placeholder="Search for a video..." className='search-input' value={searchRequest} onChange ={(event) => setSearchRequest(event.target.value)} />
<button className='search-button'>Search</button>
</form>
</div>
);
}
export default SearchBar;```
import React from "react";
import "./VideoPlayer.css";
const VideoPlayer = (props) => {
return (
<div>
<iframe
id="ytplayer"
title="MyPlayer"
type="text/html"
width="640"
height="360"
src={`https://www.youtube.com/embed/${props.videoId}?autoplay=1&origin=http://example.com`}
frameBorder="0">
</iframe>
<div className="video-details">
<h3>{props.title}</h3>
<p>{props.description}</p>
</div>
<div className="video-details">
</div>
<div className="flex-container">
{props.relatedVideos.map((video, index) => {
if(video.snippet){
return (
<div key={index} className="flex-item">
<div>
<img src={video.snippet.thumbnails.medium.url} alt="" />
</div>
<div>
<h6 >{video.snippet.title}</h6>
</div>
</div>
);
} else {
return null;
}
})}
</div>
</div>
);
}
export default VideoPlayer;
VideoPage.js
import React, {useEffect, useState } from "react";
import { Link } from "react-router-dom";
import "./VideoPage.css";
import SearchBar from "../../components/SearchBar/SearchBar";
import axios from 'axios'
import VideoPlayer from "../../components/VideoPlayer/VideoPlayer";
import { KEY } from "./../../localKey"
const VideoPage = () => {
const [searchResults, setSearchResults] = useState('');
const [videoId, setVideoId] = useState("");
const [description, setDescription] = useState("");
const [title, setTitle] = useState("");
const [relatedVideos, setRelatedVideos] = useState([]);
useEffect(() => {
getSearchResults();
},[])
async function getSearchResults(searchTerm='Bees'){
let response = await axios.get(`https://www.googleapis.com/youtube/v3/search?part=snippet&q=${searchTerm}&type=video&maxResults=1&key=${KEY}`);
setVideoId(response.data.items[0].id.videoId)
setDescription(response.data.items[0].snippet.description)
setTitle(response.data.items[0].snippet.title)
setSearchResults(response.data.items)
console.log(response.data.items)
}
useEffect(() => {
const fetchRelatedVideos = async () => {
try {
let response = await axios.get(`https://www.googleapis.com/youtube/v3/search?key=${KEY}&part=snippet&maxResults=3&type=video&relatedToVideoId=${videoId}`, {
});
setRelatedVideos(response.data.items);
} catch (error) {
console.log(error.message);
}
};
fetchRelatedVideos();
}, [videoId]);
return (
<div>
<div className="video-reg-contain"></div>
<div><SearchBar getSearchResults={getSearchResults}/></div>
<div className = 'video-contain'>
<div className="video-container">
<div className='video-player'>
<VideoPlayer videoId={videoId}
description={description}
title={title}
relatedVideos={relatedVideos}/>
</div>
</div>
</div>
</div>
);
};
export default VideoPage;

OMdb react props.data.map is not a function

I'm trying to display data from the OMdb API, but every time I try using my method nothing works.
I want to display the movie posters onto a slider using Spline.js, I was able to successfully do so whenever I manually put in the JSON data into the state but now I want to get the data from the API and I'm coming across this props.movie.map is not a function error all the way in an external component.
Heres the project on CodeSandbox just in case
https://codesandbox.io/s/github/JojoDuke/reactmoviesapp?file=/src/App.js
App.js
/* eslint-disable react-hooks/exhaustive-deps */
import React, { useState, useEffect } from 'react';
import "bootstrap/dist/css/bootstrap.min.css";
import "./App.css"
import MoviesList from "./components/MoviesList";
import ListHeading from './components/ListHeading';
import { SearchBox } from './components/SearchBox';
import AddFavourites from './components/AddFavourites';
import RemoveFavourites from './components/RemoveFavourites';
import MainMovie from './components/MainMovie';
import Navbar from './components/Navbar';
import Footer from './components/Footer';
const App = () => {
const [movies, setMovies] = useState([]);
const [searchValue, setSearchValue] = useState("");
const [favourites, setFavourites] = useState([]);
// Backup
// const getMovie = async () => {
// const url = 'http://www.omdbapi.com/?i=tt3896198&apikey=ce990560';
// const res = await fetch(url);
// const data = await res.json();
// const responseJson = JSON.parse(data);
// setMovies(responseJson);
// }
const API_KEY = "91d62f4";
const url = `http://www.omdbapi.com/?i=tt3896198&apikey=${API_KEY}`;
const getMovies = async () => {
try {
const response = await fetch(url);
const data = await response.json()
setMovies(data);
} catch (e) {
console.error(e.toString);
}
}
// FUNCTIONS
useEffect(() => {
getMovies();
}, []);
useEffect(() => {
const movieFavourites = JSON.parse(
localStorage.getItem('react-movie-app-favourites')
);
if (movieFavourites) {
setFavourites(movieFavourites);
}
}, []);
const saveToLocalStorage = (items) => {
localStorage.setItem('react-movie-app-favourites', JSON.stringify(items));
}
const addFavouriteMovie = (movie) => {
const newFavouriteList = [...favourites, movie];
setFavourites(newFavouriteList);
saveToLocalStorage(newFavouriteList);
}
const removeFavouriteMovie = (movie) => {
const newFavouriteList = favourites.filter((favourite) => favourite.imdbID !== movie.imdbID);
setFavourites(newFavouriteList);
saveToLocalStorage(newFavouriteList);
}
// FUNCTIONS CLOSE
return (
<div>
{/* Navigation Bar */}
<div>
<Navbar />
</div>
<div className="row d-flex align-items-center mb-5">
{/* Main Movie Area */}
<MainMovie/>
{/* <SearchBox
searchValue={searchValue}
setSearchValue={setSearchValue}/> */}
</div>
{/* Movies List */}
<ListHeading heading="Trending" />
<div>
<MoviesList
movies={movies}
handleFavouritesClick={addFavouriteMovie}
favouriteComponent={AddFavourites}/>
</div>
{/* List 2 */}
<div className="row d-flex align-items-center mt-4 mb-4">
<ListHeading heading="Cinetime Originals" />
</div>
<div>
<MoviesList
movies={movies}
handleFavouritesClick={addFavouriteMovie}
favouriteComponent={AddFavourites}/>
</div>
{/* List 3 */}
<div className="row d-flex align-items-center mt-4 mb-4">
<ListHeading heading="Classics" />
</div>
<div>
<MoviesList
movies={movies}
handleFavouritesClick={addFavouriteMovie}
favouriteComponent={AddFavourites}/>
</div>
<Footer />
</div>
);
};
export default App;
MoviesList.js(where I'm getting the error)
import React from 'react';
import { Splide, SplideSlide } from '#splidejs/react-splide';
//import '#splidejs/splide/dist/css/themes/splide-default.min.css';
const MoviesList = (props) => {
//const FavouriteComponent = props.favouriteComponent;
const movieSplide = props.movies.map((movie, index) => {
return(
<SplideSlide>
<div className="movie-div">
<div className="overlay"></div>
<img
className="movie-item shadow"
src={movie.Poster}
alt='movie'></img>
</div>
</SplideSlide>
);
});
return(
<Splide options={{
rewind: false,
autoWidth: true,
perPage: 6,
perMove: 2,
pagination: false,
gap: '1em',
focus: 'center',
type: 'slide',
easing: 'ease',
arrows: true
}}>
{movieSplide}
</Splide>
);
};
export default MoviesList;

How to set ratings individually with localstorage?

Okay so as you can tell,I am building a recipe app where in each recipe detail page, I can rate the the recipe...but now the problem is that when I rate one recipe now, the same rating is set for all the other recipes as well. Any idea how to fix that? Apreciate any advice...thanks so much :))
Details.js
import { useParams } from 'react-router-dom';
import './Details.css';
import React, { useEffect, useState } from 'react';
import axios from 'axios';
import Image from './vitaminDfood-1132105308-770x553.jpg';
import {Link} from 'react-router-dom'
import ReactStars from 'react-rating-stars-component'
import { RecipeContext } from './RecipeContext';
import { useContext } from 'react';
function Details() {
const [details, setDetails] = useState([]);
const { recipeId } = useParams();
const{recipes,setRecipes}=useContext(RecipeContext)
const initialRatings = JSON.parse(localStorage.getItem("rating") || "[]");
const[rating,setRating]=useState(initialRatings)
useEffect(() => {
axios
.get(`https://cookbook.ack.ee/api/v1/recipes/${recipeId}`)
.then((res) => setDetails(res.data));
});
useEffect(() => {
localStorage.setItem("rating", JSON.stringify(rating));
}, [rating])
const ratingChanged = (newRating) => {
var rate={
score:newRating
}
setRating(newRating)
axios.post(`https://cookbook.ack.ee/api/v1/recipes/${recipeId}/ratings`,rate)
.then((res) => {
console.log(res.data)
setRecipes(recipes)
})
};
return (
<>
<div className="details">
<div className="food-photo">
<img src={Image} alt="" />
<Link to="/"> <i className="fas fa-arrow-left arrow"></i></Link>
<h1>{details.name}</h1>
</div>
<div className="star-line">
{new Array(rating).fill(null).map(() => (
<i className="fas fa-star stari"/>
))}
<p className="duration"><i className="far fa-clock"></i>{details.duration}<span>min.</span></p>
</div>
<p className="info">{details.info}</p>
<h1 className="ingredience">Ingredience</h1>
<div className="ing">{details.ingredients}</div>
<h1 className="ingredience">Příprava</h1>
<p className="description">{details.description}</p>
</div>
<div className="stars">
<ReactStars
classNames="star"
size={48}
onChange={ratingChanged}
count={5}
value={1}
edit
/>
</div>
</>
);
}
export default Details;
You have a couple options:
Store a different localStorage key for each recipe
Just have one large "ratings" key in localStorage and make that an object keyed off of your recipeId.
I think the first option is the most straightforward and can be accomplished with these minor modifications:
const initialRatings = JSON.parse(localStorage.getItem(`ratings-${recipeId}`) || "[]");
useEffect(() => {
localStorage.setItem(`ratings-${recipeId}`, JSON.stringify(rating));
}, [rating, recipeId])

how to display Axios fetch data

Hi people Am new in react js, i have a problem in display data , in my application i fetched data but i couldn't be display in web page don't know where Am wrong please try to fix my error or tell me what should i do?
console data
https://ibb.co/1MfgDgW
Star.js
import Axios from 'axios';
import React, { useState, useEffect } from 'react';
import './Star.css';
import Planet from './Planet';
import People from './People';
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() {
const res = await Axios.get("https://swapi.dev/api/people/?format=json");
console.log(res.data.results);
setPeople(res.data.results);
}
async function fetchPlanet() {
const res = await Axios.get("https://swapi.dev/api/planets/?format=json");
console.log(res.data.results);
setPlanet(res.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>
<People people={people}/>
<Planet planet={planet}/>
</div>
</div>
)
}
export default Star;
People.js
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.data.results[0].name}</h4>
</div>
</div>
</div>
)
})}
</div>
);
};
export default People;
Planet.js
import React from 'react';
const Planet = (props) => {
const { data } = props;
return (
<div className="row">
{data && data.map((planet, i) => {
return (
<div className="col-md-3" key={i}>
<div className="card">
<div className="card-body">
<h4>{planet.data.results[0].name}</h4>
</div>
</div>
</div>
)
})}
</div>
);
};
export default Planet;
App.js
This is the App.js file where i include my all components
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={people}
planet={planet}
/>
<People data={people} />
<Planet data={planet} />
</div>
);
}
export default App;
You pass people and planet as props, but using it as data prop:
<Planet planet={planet}/>
const Planet = (props) => {
// change to this, people too
const { planet } = props;
};
You're passing people and planet as props to App but you're performing the fetching in Star.js.
You might need to restructure your app so that data fetching is done by App and then pass down everything as props.
function App(props) {
const { people, planet } = props;
return (
<div className="App">
<Star people={people} planet={planet} />
<People data={people} />
<Planet data={planet} />
</div>
);
}

not able to display console data in web page

i am beginner in react . when i fetch request from API, i got data in console ,but when i am trying to display data in web page in that time data isn't show.
I want to display data in web page.
here is my console log
https://ibb.co/YLmLQz1
App.js
import React from 'react';
import './App.css';
import Header from './components/Header';
import Movie from './components/Movies';
const App = () => {
return (
<div className="App">
<Header />
<div className='container'>
<Movie />
</div>
</div>
);
}
export default App;
Header.js
In header file i created my navbar and search form
import React, { useState } from 'react'
const Header = () => {
const [search, setSearch] = useState('');
return (
<div className="jumbotron">
<h1 className="display-1">
<i className="material-icons brand-icon">LatestMovie</i> Movie
</h1>
<div className="input-group w-50 mx-auto">
<input
type="text"
className="form-control"
placeholder="Search Your Movie..."
value={search}
onChange={e => setSearch(e.target.value)}
/>
<div className="input-group-append">
<button className="btn btn-dark">
Search Movie
</button>
</div>
</div>
</div>
)
}
export default Header;
Movies.js
here i fetch my movies request throght axios
import React, { useEffect, useState } from 'react'
import Axios from 'axios';
const Movie = () => {
const [movies, setMovie] = useState([]);
const apiurl = "http://www.omdbapi.com/?apikey=642b793e&s=marvel"
const getMovies = async () => {
const res = await Axios.get(apiurl);
console.log(res);
setMovie(res.data.hits);
}
useEffect(() => {
getMovies();
}, []);
return (
<div className='row'>
{
movies && movies.map(movie => (
<div className='col-md-3'>
<div className='card'>
<div className='card-body'>
<h4>{movie.Year}</h4>
</div>
</div>
</div>
))
}
</div>
)
}
export default Movie;

Resources