React Hook called in function - javascript

i am newbi to react js i was trying to learn by doing project , i was building basic ecom ui with items
i was trying to create a basket to add the item into the cart , but i faced that problem
React Hook "useStateValue" is called in function "product" which is neither a React function component or a custom React Hook function react-hooks/rules-of-hooksmponent or a custom React Hook function
import React from 'react';
import "./Product.css"
import { useStateValue } from "./StateProvider";
function product({id,title,image,price,rating}) {
const [{basket},dispatch] = useStateValue();
const addToBasket = () => {
dispatch({
type: "ADD_TO_BASKET",
item:{
id:id,
title:title,
image:image,
price:price,
rating:rating
},
})
};
return (
<div className="product">
<div className="product__info" >
<p>{title}</p>
<p className="product__price">
<small>$</small>
<strong> {price} </strong>
</p>
<div className="product__rating">
{Array(rating)
.fill( )
.map((_) => (
<p>-</p>
))}
</div>
</div>
<img src={image} alt=""/>
<button onClick={addToBasket} className="product__button"> Add to basket </button>
</div>
);
}
export default product
................................
import React from 'react';
import "./Product.css"
import { useStateValue } from "./StateProvider";
function product({id,title,image,price,rating})
{
const [{basket},dispatch] = useStateValue();
const addToBasket = () => {
dispatch({
type: "ADD_TO_BASKET",
item:{
id:id,
title:title,
image:image,
price:price,
rating:rating
},
})
};
return (
<div className="product">
<div className="product__info" >
<p>{title}</p>
<p className="product__price">
<small>$</small>
<strong> {price} </strong>
</p>
<div className="product__rating">
{Array(rating)
.fill( )
.map((_) => (
<p>-</p>
))}
</div>
</div>
<img src={image} alt=""/>
<button onClick={addToBasket} className="product__button"> Add to basket </button>
</div>
);
}
export default product
.....................................
import React from 'react';
import Product from "./Product";
import "./Home.css";
function Home() {
return (
<div className="home">
<img class="home__image" src="https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Ftse4.mm.bing.net%2Fth%3Fid%3DOIP.3U6xnN8wOOQ5atG6MO907wHaEK%26pid%3DApi&f=1"/>
<div className="home__row">
<Product
id="300"
title="Argan oil"
price={11.96}
rating={5}
image="https://i.pinimg.com/originals/e6/13/0e/e6130ed7d4820b7eba0a1ba7a631abea.jpg"
alt="" />
<Product
id="300"
title="Argan oil"
price={11.96}
rating={5}
image="https://i.pinimg.com/736x/ef/c4/01/efc4017b4340dfc35a98ca2235189759.jpg"
alt="" />
<Product
id="300"
title="Argan oil"
price={11.96}
rating={5}
image="https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Fwww.byrdie.com%2Fthmb%2F6a2mRHTbEwSWrTOTG1yT5gFDxFs%3D%2F700x700%2Ffilters%3Ano_upscale()%3Amax_bytes(150000)%3Astrip_icc()%2Fcdn.cliqueinc.com__cache__posts__269825__iherb-natural-beauty-products-269825-1539195561186-product.700x0c-6534d2dd4ba1409b84d89684001853df.jpg&f=1&nofb=1"
alt="" />
<Product
id="300"
title="Argan oil"
price={11.96}
rating={5}
image="https://s3.images-iherb.com/sre/sre01007/r/1.jpg"
alt="" />
<Product
id="300"
title="Argan oil"
price={11.96}
rating={5}
image="https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Fi.pinimg.com%2Foriginals%2Fb7%2Fb4%2F72%2Fb7b47228df40d8a2759f30aa778ff31c.jpg&f=1&nofb=1"
alt="" />
<Product
id="300"
title="Argan oil"
price={11.96}
rating={5}
image="https://s3.images-iherb.com/now/now04920/r/9.jpg"
alt="" />
</div>
</div>
)
}
export default Home;

I changed two things and error fixed
first in Product.js I changed name of function to Product(capitialzing)
second in reducer.js I changed ...action.item to action.item

1.change the function product to Product in component Product.js that is all and it should work.

its a very simple fix, so the issue is the useStateValue() must start with a capital letter. change it to "UseStateValue()" in the stateProvider.js file and then run it. the compiler will let you know where you have to make the changes and run it. it will solve it

I assume that you're using Context API and creating amazon clone from clever programmer youtube channel.
This error comes when <Home /> component not placed inside <StateProvider> component
Here is my StateProvider.js
import React, { useContext, createContext, useReducer } from 'react';
export const StateContext = createContext();
function StateProvider({ reducer, initialState, children}) {
return (
<StateContext.Provider value={ useReducer(reducer, initialState) }>
{ children }
</StateContext.Provider>
);
}
export const useStateValue = () => useContext(StateContext);
export default StateProvider;
App.js
import React from "react";
import Header from "./components/Header/Header";
import Home from "./components/Home/Home";
import { BrowserRouter, Routes, Route } from "react-router-dom";
function App() {
return (
<StateProvider reducer={Reducer} initialState={initialState} >
<div className="app">
<BrowserRouter>
<Routes>
<Route path="/" element={
<>
<Header />
<Home />
</>
} />
</Routes>
</BrowserRouter>
</div>
</StateProvider>
);
}
export default App;
So kindly check whether the <Home /> component is children of <StateProvider>. Only the child component of StateProvider can access useStateValue() hook.

Related

pass in props into component to render

// Warning: Cannot read properties of undefined (reading 'params')
// im try to get movie_id from movielist.js to view single movie on movie.js onclicking view review
// basically my error is from inability to pass the props into movie.js
//in nav/index.js
import { BrowserRouter as Router, Routes, Route, useParams} from "react-router-dom";
import Navbar from './navbar';
import MovieList from "../components/movie-list"
import Movie from "../components/movie"
const Nav = () => {
return (
<Router>
<Navbar/>
<Routes>
<Route exact path={'/'} element={<MovieList/>}/>
<Route path='/movies/:id/' element={<Movie props={useParams()} />} />
</Routes>
</Router>
)}
//in movielist.js
import React, {useState, useEffect} from 'react'
import MovieDataService from "../services/movie"
import { Link } from 'react-router-dom'
const MovieList = () => {
....
return (
<div>
....
<div>
{movies.map((movie)=>{
return(
<div className="card" key={movie._id}>
<div className="card-container">
<div className='card-img'>
<img src={movie.poster+"/100px180"} alt=""/>
</div>
<div className="card-body">
<h1>{movie.title}</h1>
<h2>Rating:{movie.rated}</h2>
<p>{movie.plot}</p>
<Link to={"/movies/"+movie._id}>View Review</Link>
</div>
</div>
</div>
);
})}
</div>
</div>
)
}
// in movie.js
import React, { useState, useEffect } from 'react'
import MovieDataService from '../services/movie'
import { Link } from 'react-router-dom'
const Movie = (props) => {
useEffect(()=>{
getMovie(props.match.params.id)
},[props.match.params.id]) //won't call getMovie Multiple times unless id is updated.
return (
<div>
<div className="card-container">
<div className='card-img'>
<img src={movie.poster+"/100px250"} alt=""/>
</div>
<div className="card-body">
<h1>{movie.title}</h1>
<p>{movie.plot}</p>
{props.user && <Link to={"/movies/"+props.match.params.id+"/review"}>Add Review</Link>
}
</div>
</div>
);
})}
</div>
</div>
)
}
Use useParams() hook to get url params.
const {id} = useParams()
useEffect(()=>{
getMovie(id)
},[id])
replace props.match.params.id with id everywhere

how to connect two component when i click on submit button

I have some user components on which I used the navigation component and I am routing two components on it. when I click on the Device.js component button it should remove device.js and it should redirect to the Keyregister.js component which is having navigation component in it .It should change the value according to the props sent to it. But it is not happening.
user.js
import React from "react";
import { Route, Switch } from "react-router";
import "./User.css";
import Navigation from "./Dashboard/Navigation";
import AuthModel from "./Dashboard/AuthModel";
import DeviceDetails from "./Dashboard/DeviceDetails";
function User() {
return (
<>
<Navigation
link1={""}
link2={"Authmodel"}
link3={"Requests"}
link1name={"Key Status"}
link2name={"Key Upload"}
link3name={"KEY DOWNLOAD"}
/>
<Switch>
<Route path="/User/Dashboard/AuthModel" component={AuthModel} />
<Route path="/User/Dashboard/DeviceDetails" component={DeviceDetails} />
</Switch>
</>
);
}
export default User;
Navigation.js
import React from "react";
import "./Navigation.css";
import { Link } from "react-router-dom";
import { useHistory } from "react-router";
import { Image } from "react-bootstrap";
import EvoVert from "../../../Resources/EvoluteVert.png";
function Navigation(props) {
const history = useHistory();
const handleLogout = (e) => {
e.preventDefault();
localStorage.removeItem("accessToken");
localStorage.removeItem("roleType");
history.push("/");
};
return (
<>
<main classMain="main">
<aside className="sidebar ">
<Image className="Evo-logo" src={EvoVert} />
<nav className="nav">
<ul style={{ textDecoration: "none" }}>
<li>
<Link to={`/User/Dashboard/${props.link2}`}>
{props.link2name}
</Link>
</li>
<li>
<Link to={`/User/Dashboard/${props.link1}`}>
{props.link1name}
</Link>
</li>
<li>
<Link to={`/User/Dashboard/${props.link3}`}>
{props.link3name}
</Link>
</li>
</ul>
</nav>
</aside>
</main>
</>
);
}
export default Navigation;
Device.js
import React, { useState, useEffect } from "react";
import { Form } from "react-bootstrap";
import "./Dashboard.css";
import { useHistory } from "react-router";
import KeyRegister from "./KeyRegister";
function DeviceDetails() {
const history = useHistory();
const [visible, setvisible] = useState(true);
const [serialNum, setSerialNum] = useState("");
const [slot, setSlot] = useState("");
const frmsubmit = (e) => {};
return (
<>
<section className="device-Details_Dashboard">
<div className="container">
<div
className="heading"
style={{
color: "#312450",
fontWeight: "400",
fontSize: "35px",
padding: "1rem",
}}
>
DEVICE DETAILS
</div>
<Form onSubmit={frmsubmit}>
<div>
<div className="device-details-box">
<label>Serial Number</label>
<br />
<input
type="text"
value={serialNum}
onChange={(e) => setSerialNum(e.target.value)}
/>
</div>
<div className="device-details-box">
<label>Slot Number</label>
<br />
<input
type="text"
value={slot}
onChange={(e) => setSlot(e.target.value)}
/>
</div>
</div>
<button className="devDetSub" onClick={frmsubmit}>
<span>SUBMIT</span>
</button>
</Form>
</div>
</section>
{visible && <KeyRegister />}
</>
);
}
export default DeviceDetails;
KeyRegister.js
import React, { useState, useEffect } from "react";
import "./Navigation.css";
import { Route, Switch } from "react-router";
import DUPKT from "./DUPKT";
import MasterSession from "./MasterSession";
import AES from "./AES";
import Navigation from "./Navigation";
function KeyRegister() {
return (
<>
<Navigation
link1={"DUPKT"}
link2={"MasterSession"}
link3={"AES"}
link1name={"DUPKT"}
link2name={"MASTER KEY"}
link3name={"AES"}
/>
<main classMain="main">
<Switch>
<Route path="/User/Dashboard/DUPKT" component={DUPKT} exact />
<Route
path="/User/Dashboard/MasterSession"
component={MasterSession}
exact
/>
<Route path="/User/Dashboard/AES" component={AES} exact />
</Switch>
</main>
</>
);
}
export default KeyRegister;
I cannot see anywhere in your naviagation component props you are passing device details.
<Navigation
link1={""}
link2={"Authmodel"}
link3={"Requests"}
link1name={"Key Status"}
link2name={"Key Upload"}
link3name={"KEY DOWNLOAD"} //should have device details in props
/>

No error showing on console, still CardELement is not rendering?

Coding a project using React. It's been 3 days I've looking for a solution. I had been learning coding and trying to integrate stripe payment option on my web-app. However, unable to get the proper result. Searched a lot, found no solution.
Code is below :
App.js
import { Elements } from '#stripe/react-stripe-js';
import { loadStripe } from '#stripe/stripe-js';
import { useEffect } from 'react';
import { BrowserRouter, Route, Routes } from 'react-router-dom';
import './App.css';
import Checkout from './Checkout';
import { auth } from './firebase';
import Header from './Header';
import Home from './Home';
import Login from './Login';
import Payment from './Payment';
import { useStateValue } from './StateProvider';
const promise = loadStripe("pk_test_51KtYdQSJwVy1hdNxUPD5HK8KcKbLDVSic6q6jfdPxuSLYiCjuwzBfE8Eo5u0zVclLgPP33InVTjAyM4rZP3ouWB9009AL3lsZ6");
function App() {
const [{ }, dispatch] = useStateValue();
useEffect(() => {
auth.onAuthStateChanged(authUser => {
console.log("THE USER IS >>>>> ", authUser);
if (authUser) {
dispatch({
type: "SET_USER",
user: authUser
});
}
else {
dispatch({
type: "SET_USER",
user: null
})
}
})
}, []);
return (
<BrowserRouter>
<div className="App">
<Header />
{console.log("load stripe>>>>>>>>",promise)}
<Routes>
<Route path="/payment" element={
<Elements stripe={promise}>
<Payment />
</Elements>
} />
<Route path="/login" element={<Login />} />
<Route path="/checkout" element={<Checkout />} />
<Route path="/" element={<Home />} />
</Routes>
</div>
</BrowserRouter>
);
}
export default App;
Component in which using Stripe and CardElement (Payment.js) :
import { CardElement, useElements, useStripe } from "#stripe/react-stripe-js";
import React, { useState } from "react";
import CurrencyFormat from "react-currency-format";
import { Link } from "react-router-dom";
import CheckoutProduct from "./CheckoutProduct";
import "./Payment.css";
import { getBasketTotal } from "./reducer";
import { useStateValue } from "./StateProvider";
function Payment() {
const [{ basket, user }, dispatch] = useStateValue();
const stripe = useStripe();
const elements = useElements();
const [error,setError]=useState(null);
const [disabled,setDisabled]=useState(true);
const [succeeded,setSucceeded]=useState(false);
const [processing,setProcessing]=useState("");
const handleSubmit = event => {
//do all the stripe stuff
event.preventDefault();
}
const handleChange = event =>{
// Listen for changes in the CardElement
// and display any errors as the customer types card details
setDisabled(event.empty);
setError(event.error ? event.error.message : "");
}
return (
<div className="payment">
<div className="payment__container">
<h1>
Checkout ({<Link to="/checkout">{basket?.length} items</Link>})
</h1>
{/* Payment section - delivery address */}
<div className="payment__section">
<div className="payment__title">
<h3>Delivery Address</h3>
</div>
<div className="payment__address">
<p>{user?.email}</p>
<p>786 Chaurangi Marg</p>
<p>Delhi, India</p>
</div>
</div>
{/* Payment section - Review items */}
<div className="payment__section">
<div className="payment__title">
<h3>Review Items and Delivery</h3>
</div>
<div className="payment__items">
{basket.map(item =>
<CheckoutProduct
id={item.id}
title={item.title}
price={item.price}
rating={item.raing} />
)}
</div>
</div>
{/* Payment section - payment method */}
<div className="payment__section">
<div className="payment__title">
<h3>Payment Method</h3>
</div>
<div className="payment__details">
<form onSubmit={handleSubmit}>
{/*<CardElement />*/}
<div className="card__element">
<CardElement />
</div>
<div className="payment__priceContainer">
<CurrencyFormat
renderText={(value)=>(
<>
<h3>Order Total: {value}</h3>
</>
)}
decimalScale={2}
value={getBasketTotal(basket)}
displayType={"text"}
thousandSeparator={true}
prefix={"₹"}
/>
<button disabled={processing || disabled || succeeded}>
<span>{processing ? <p>Processing</p> : "Buy Now"}</span>
</button>
</div>
{error && <div>{error}</div> }
</form>
</div>
</div>
</div>
</div>
)
}
export default Payment;

Functional component is not being rendered

I am trying to display the songs but for some reason my songs component is not even being executed. The console.log statement inside the Songs component is also not being logged to console. Also no errors of any sort are detected at all.
Here is my body component from which I am calling the Songs component
import './body.css'
import React from 'react'
import Header from './Header'
import { useStateValue } from './StateProvider';
import FavoriteIcon from '#material-ui/icons/Favorite';
import PlayCircleFilledIcon from '#material-ui/icons/PlayCircleFilled';
import MoreHorizIcon from '#material-ui/icons/MoreHoriz';
import Songs from './Songs.js'
function Body( {spotify}) {
const [{recently_played},dispatch] = useStateValue();
return (
<div className="body">
<Header spotify={spotify} />
<div className="body__info">
<img src={recently_played?.images[0].url} alt=""/>
<div className="body__infotext">
<strong>PLAYLIST</strong>
<h2>On Repeat</h2>
<p>{recently_played?.description}</p>
</div>
</div>
<div className="body__songs">
<div className="body__icons">
<PlayCircleFilledIcon className="body__shuffle"/>
<FavoriteIcon fontSize="large"/>
<MoreHorizIcon />
</div>
{recently_played?.tracks.items.map(item=>{
<Songs track={item.track} />
})}
</div>
</div>
)
}
export default Body
Here is the Songs component
import React from "react";
import './SongRow.css'
function Songs({ track }) {
console.log(track);
return (
<div className="songRow" >
<img className="songRow__album" src={track.album.images[0].url} alt="" />
<div className="songRow__info">
<h1>{track.name}</h1>
<p>
{track.artists.map((artist) => artist.name).join(", ")} -{" "}
{track.album.name}
</p>
</div>
</div>
);
}
export default Songs;
You are not returning anything inside the map
{recently_played?.tracks.items.map(item => {
return <Songs track={item.track} />;
})}
[or] use the shorthand version of arrow function
{recently_played?.tracks.items.map(item => <Songs track={item.track} />)}

How can I use nested routes with props for a child component

I'm building an react app where I have a feed component and the feed component consists of array of post components. The post component contains a link in it for viewing the full post component. I'm not able to pass the respective props to the full post component. I'm not able to do a nested route for the fullpost component.
this is my layout component
import React, { Component } from "react";
import Header from "../Header/Header";
import classes from "./Layout.css";
import { Route, Switch } from "react-router-dom";
import FullPost from "../Feed/FullPost/FullPost";
import axios from "axios";
import Feed from "../Feed/Feed";
class Layout extends Component {
state = {
users: [],
};
componentDidMount() {
axios
.get("https://goodwill-60d8a.firebaseio.com/Users.json")
.then((response) => {
this.setState({ users: response.data });
});
}
render() {
console.log(this.state.users);
return (
<div className={classes.main}>
<div>
<Header />
</div>
<div className={classes.content}>
<Switch>
<Route
path="/"
exact
render={() => <Feed users={this.state.users} />}
/>
<Route path="/fullpost" exact render={() => <FullPost />} />
</Switch>
</div>
</div>
);
}
}
export default Layout;
FEED component
import React from "react";
import Post from "./Post/Post";
import classes from "./Feed.css";
const feed = (props) => {
const feedItems = Object.keys(props.users).map((key) => ({
id: key,
...props.users[key],
}));
return (
<div className={classes.feed}>
{feedItems.map((items) => (
<Post
key={items.id}
profilename={items.profileName}
profilepic={items.profilePic}
timestamp={items.timeStamp}
contentimage={items.contentImage}
contenttext={items.contentText}
trend={items.trend}
></Post>
))}
</div>
);
};
export default feed;
Post component
import React from "react";
import classes from "./Post.css";
import ShareButton from "../../UI/ShareButton/ShareButton";
import { Link } from "react-router-dom";
const post = (props) => {
return (
<div className={classes.post}>
<div className={classes.header}>
<div className={classes.profileimage}>
<img className={classes.pic} src={props.profilepic} alt="" />
</div>
<div className={classes.name}>{props.profilename}</div>
<div className={classes.timestamp}>{props.timestamp}</div>
</div>
<div className={classes.container}>
<div className={classes.image}>
<img src={props.contentimage} alt="" />
</div>
<div>
<div className={classes.text}>
<span>{props.contenttext}</span>
</div>
<div className={classes.fullpost}>
<Link to="/fullpost" {...props}>
See Full Post
</Link>
</div>
</div>
</div>
<div className={classes.footer}>
<div className={classes.trend}>
<span>{props.trend}</span>
</div>
<ShareButton />
</div>
</div>
);
};
export default post;
Full Post component
import React from "react";
import classes from "./FullPost.css";
import pic from "../../../Assets/Images/self.jpg";
import { Link } from "react-router-dom";
const fullPost = (props) => {
return (
<div className={classes.fullpost_container}>
<div className={classes.photo_container}>
<img src={props.profilepic} alt=" " />
</div>
<div className={classes.sidebar}>
<div className={classes.profileimage}>
<img src={props.profilePic} alt="" />
</div>
<div className={classes.profilename}>Tony Kroos</div>
<div className={classes.timestamp}>3 Hours Ago</div>
</div>
<div className={classes.feedlink}>
<Link to="/" className={classes.feedlink_text}>
See more posts
</Link>
</div>
</div>
);
};
export default fullPost;

Categories