not able to display console data in web page - reactjs

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;

Related

How to display the current data and previous data entered via form in react

Thanks for the help in advance. Currently, I am learning react. As a part of learning, I'm working on a basic expense listing app. In it, I was able to list the data entered through the form. But the problem is that when the new data is entered the previous one gets disappeared. I want to list the current as well as the previous data. Can anyone help me to resolve this.
App.js
import React, { useState, Fragment } from "react";
import ExpenseAddForm from "./ExpenseAddForm/ExpenseAddform";
import ExpenseList from "./ExpenseList/ExpenseList";
const App = () => {
const [expensesData, setExpensesData] = useState("");
const FormData = (datas) => {
setExpensesData(datas);
};
return (
<Fragment>
<div className="new-expense">
<ExpenseAddForm FormData={FormData} />
</div>
<ExpenseList listDatas={expensesData}></ExpenseList>
</Fragment>
);
};
export default App;
ExpenseAddform.js
import React, { useState } from "react";
import "./ExpenseAddForm.css";
const ExpenseAddForm = (props) => {
const [title, setTitle] = useState("");
const [amount, setAmount] = useState("");
const [date, setDate] = useState("");
const titleHandler = (e) => {
setTitle(e.target.value);
};
const amountHandler = (e) => {
setAmount(e.target.value);
};
const dateHandler = (e) => {
setDate(e.target.value);
};
const formSubmitHandler = (event) => {
event.preventDefault();
const formData = {
title: title,
amount: amount,
date: date,
};
props.FormData(formData);
setTitle("");
setAmount("");
setDate("");
};
return (
<form onSubmit={formSubmitHandler}>
<div className="new-expense__controls">
<div className="new-expense__control">
<label>Title</label>
<input type="text" onChange={titleHandler} value={title} />
</div>
<div className="new-expense__control">
<label>Amount</label>
<input type="number" onChange={amountHandler} value={amount} />
</div>
<div className="new-expense__control">
<label>Date</label>
<input type="date" onChange={dateHandler} value={date} />
</div>
</div>
<div className="new-expense__actions">
<button type="submit">Cancel</button>
<button type="submit">Add Expense</button>
</div>
</form>
);
};
export default ExpenseAddForm;
ExpenseList.js
import React from "react";
import ExpenseItem from "./ExpenseItem/ExpenseItem";
import ExpenseDateFilter from "./ExpenseDateFilter/ExpenseDateFilter";
import "./ExpenseList.css";
const ExpenseList = (props) => {
return (
<div className="expenses">
<ExpenseDateFilter />
<ExpenseItem expenseInfos={props.listDatas} />
</div>
);
};
export default ExpenseList;
ExpenseItem.js
import React from "react";
// import ExpenseDate from "../ExpenseDate/ExpenseDate";
import "./ExpenseItem.css";
const ExpenseItem = (props) => {
return (
<div className="expense-item">
{/* <ExpenseDate enteredDate={props.expenseInfos.date} /> */}
<div className="expense-item__description">
<h2>{props.expenseInfos.title}</h2>
{/* <div className="expense-item__price">${props.expenseInfos.amount}</div> */}
</div>
</div>
);
};
export default ExpenseItem;
ExpenseDateFilter.js
import React from "react";
const ExpenseDateFilter = () => {
return (
<div className="expenses-filter">
<div className="expenses-filter__control">
<label>Filter by year</label>
<select>
<option value="2022">2022</option>
<option value="2021">2021</option>
<option value="2020">2020</option>
<option value="2019">2019</option>
</select>
</div>
</div>
);
};
export default ExpenseDateFilter;
The problem with your code is on each submit your overriding the expensesData with the new data
instead you need to do
const FormData = (datas) => {
setExpensesData([...expensesData,datas]);
};
now you have list of data next you need to handle multiple expenses data in ExpenseList.js
{props.listDatas.map((data,key)=>
<ExpenseItem expenseInfos={data} />
)}
and it should be done here is a link of a working example https://codesandbox.io/s/xenodochial-grass-g2k1fh?file=/src/App.js:467-476

How can fix notification problem in axios search method?

I have such a problem. I want to receive a notification after entering a keyword in the input and submitting. If there is a movie, then the movies should be listed, if there is not movies, let the toast notification appear. But the problem, even movies there are still toast works. How can i fix it? I want only when there are no movies for example search results doesnt find any film that toast will come. But toast comes every moment
import React, { useState } from "react";
import axios from "axios";
import { API_KEY } from "../../utils/api";
import MovieItem from "../../components/MovieItem/MovieItem";
import { Button, Input, Form } from "antd";
import "antd/dist/antd.min.css";
import "./Search.scss";
import Loader from "../../components/Loader/Loader";
import { toast } from "react-toastify";
const Search = () => {
const [movies, setMovies] = useState([]);
const [searchTerm, setSearchTerm] = useState("");
const [loading, setLoading] = useState(false);
const fetchSearch = () => {
setLoading(true)
axios
.get(
`https://api.themoviedb.org/3/search/movie?api_key=${API_KEY}&language=en-US&query=${searchTerm}&page=1&include_adult=false`
)
.then((res) => res.data)
.then((res) => {
if (!res.errors) {
setMovies(res.results);
setLoading(false)
if (movies.length === 0) {
toast("Movies doesnt find");
}
setSearchTerm("");
console.log("yes");
} else {
setMovies([]);
console.log("no");
}
});
};
const handleChange = (e) => {
setSearchTerm(e.target.value);
};
return (
<>
<div className="search">
<div className="container">
<div className="row">
<div className="col-lg-12 mb-3 mt-3">
<h2>Suggest me</h2>
</div>
<Form onFinish={fetchSearch}>
<Form.Item>
<Input
value={searchTerm}
onChange={handleChange}
placeholder="Search Movies"
/>
</Form.Item>
<Button htmlType="submit">Search</Button>
</Form>
</div>
</div>
</div>
<div className="movies">
<div className="container-fluid">
<div className="row">
{loading
?
<Loader/>
: movies?.map((movie, index) => (
<div className="col-lg-3 p-3" key={index}>
<MovieItem movie={movie} page='top_Rated'/>
</div>
))}
</div>
</div>
</div>
</>
);
};
export default Search;
Problem is solved. Res.results.length was my problem's solution

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

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

how to get input value of a json data when submitted

I have json data file. I want to make a search with the names of the data and display the typed names when I click the search button.
I get the value of input in the console when I type something however I am not able to display it on the screen
How can I display the value of this input ?
my code is below
PostResults.jsx
import React from "react";
const PostResults = (props) => {
const {name} = props.posts
return(
<div className="">
<p className="titles">{name}</p>
</div>
)
}
export default PostResults
Posts.jsx
import React, { useState, useEffect } from "react";
import PostResults from './PostResults'
const Posts = (props) => {
const [posts, setPosts] = useState([]);
const [searchTerm,setSearchTerm]=useState([]);
const getData = () => {
fetch('data.json')
.then(response => {
return response.json()
//console.log(response)
})
.then(data => {
setPosts(data)
console.log(data)
})
}
useEffect(() => {
getData()
},[])
const submitHandler = (event) => {
event.preventDefault()
{searchTerm ? searchTerm : console.log("none")}
}
return(
<div className="">
<input
type="text"
placeholder="Search Anything"
name="query"
onChange={e => setSearchTerm(e.target.value)}
className="search-input"
/>
<button
onClick={submitHandler}
type="submit"
className="search-button"
>
<i className="fas fa-search"></i>
</button>
{posts.map(posts => (
<PostResults key={posts.id} posts={posts}/>
))}
</div>
)
}
export default Posts
App.jsx
import React from "react";
import "./style.css";
import 'bootstrap/dist/css/bootstrap.min.css'
import Posts from './components/Posts'
export default function App() {
return (
<div className="container">
<div className="row">
< Posts />
</div>
</div>
);
}

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>
);
}

Resources