Commerce JS, generateToken returning "Material-UI: A component is changing the controlled value state of Select to be uncontrolled." - javascript

This is where i generate the token
import React, { useState, useEffect } from 'react';
import { Paper, Stepper, Step, StepLabel, Typography, CircularProgress, Divider, Button } from '#material-ui/core';
import { commerce } from '../../../lib/commerce';
import useStyles from './styles';
import AddressForm from '../AddressForm';
import PaymentForm from '../PaymentForm';
const steps = ['Shipping address', 'Payment details'];
const Checkout = ({ cart }) => {
const [activeStep, setActiveStep] = useState(0);
const [checkoutToken, setCheckoutToken] = useState(null);
const classes = useStyles();
useEffect(() => {
if (cart.id) {
const generateToken = async () => {
try {
const token = await commerce.checkout.generateToken(cart.id, { type: 'cart' });
setCheckoutToken(token)
} catch (error){
console.log(error);
}
};
generateToken();
}
}, [cart]);
const Confirmation = () => (
<div>
Confirmation
</div>
)
const Form = () => activeStep === 0
? <AddressForm checkoutToken={checkoutToken} />
: <PaymentForm />
return (
<>
<div className={classes.toolbar} />
<main className={classes.layout} >
<Paper className={classes.paper}>
<Typography variant='h4' align='center'>Checkout</Typography>
<Stepper activeStep={activeStep} className={classes.stepper}>
{steps.map((step) => (
<Step key={step}>
<StepLabel>{step}</StepLabel>
</Step>
))}
</Stepper>
{activeStep === steps.length ? <Confirmation /> : checkoutToken && <Form />}
</Paper>
</main>
</>
)
}
export default Checkout
Here is my App.js
import React, { useState, useEffect, Fragment } from 'react'
import { commerce } from './lib/commerce';
import { Products, Navbar, Cart, Checkout } from './components';
import { BrowserRouter as Router, Routes, Route} from 'react-router-dom';
const App = () => {
const [products, setProducts] = useState([]);
const [cart, setCart] = useState({});
const fetchProducts = async () => {
const { data } = await commerce.products.list();
setProducts(data);
}
const fetchCart = async () => {
setCart(await commerce.cart.retrieve())
}
const handleAddToCart = async ( productId, quantity) =>{
const { cart } = await commerce.cart.add(productId, quantity);
setCart(cart);
}
const handleUpdateCartQty = async (productId, quantity) => {
const { cart } = await commerce.cart.update(productId, { quantity });
setCart(cart);
}
const handleRemoveFromCart = async (productId) => {
const { cart } = await commerce.cart.remove(productId);
setCart(cart);
}
const handleEmptyCart = async () => {
const { cart } = await commerce.cart.empty();
setCart(cart);
}
useEffect(() => {
fetchProducts();
fetchCart();
}, []);
return (
<Router>
<div>
<Navbar totalItems={cart.total_items} />
<Routes>
<Route exact path='/' element={<Products products={products} onAddToCart={handleAddToCart} />} />
<Route exact path='/cart' element={<Cart cart={cart} handleUpdateCartQty={handleUpdateCartQty} handleAddToCart={handleAddToCart} handleRemoveFromCart={handleRemoveFromCart} handleEmptyCart={handleEmptyCart} />} />
<Route exact path='/checkout' element={ <Checkout cart={cart} />} />
</Routes>
</div>
</Router>
)
}
export default App;
And here is my cart.jsx incase their is anything relevant there
import React from 'react'
import { Container, Typography, Button, Grid} from '#material-ui/core';
import { Link } from 'react-router-dom';
import useStyles from './styles';
import CartItem from './CartItem/CartItem';
const Cart = ({ cart, handleUpdateCartQty, handleRemoveFromCart, handleEmptyCart }) => {
const classes = useStyles();
const EmptyCart = () => (
<Typography variant='subtitle1'>
You have no items in your shopping cart.
<Link to='/' className={classes.link}>Add Items!</Link>
</Typography>
);
const FilledCart = () => (
<>
<Grid container spacing={3}>
{ cart.line_items.map((item) => (
<Grid item xs={12} sm={4} key={item.id}>
<CartItem item={item} onUpdateCartQty={handleUpdateCartQty} onRemoveFromCart={handleRemoveFromCart} />
</Grid>
))}
</Grid>
<div className={classes.cardDetails}>
<Typography variant='h4'>
Subtotal: {cart.subtotal.formatted_with_symbol}
<div>
<Button className={classes.emptyButton} size='large' type='button' variant='contained' color='secondary' onClick={handleEmptyCart}>
Empty Cart
</Button>
<Button component={Link} to='/checkout' className={classes.checkoutButton} size='large' type='button' variant='contained' color='primary'>
Checkout
</Button>
</div>
</Typography>
</div>
</>
);
// Wait for cart to load items
if(!cart.line_items){
return '...loading';
}
return (
<Container>
<div className={classes.toolbar} />
<Typography className={classes.title} varaint='h3' gutterBottom >Your Shopping Cart</Typography>
{ !cart.line_items.length ? <EmptyCart /> : <FilledCart />}
</Container>
)
}
export default Cart
[error messages][1]
[1]: https://i.stack.imgur.com/vlard.png
Warning: Expected onSubmit listener to be a function, instead got a
value of string type. form
FormProvider#http://localhost:3000/static/js/bundle.js:76722:7
AddressForm#http://localhost:3000/static/js/bundle.js:1096:7 Form div
Paper#http://localhost:3000/static/js/bundle.js:12332:17
WithStyles#http://localhost:3000/static/js/bundle.js:19639:25 main
Checkout#http://localhost:3000/static/js/bundle.js:1332:7
Routes#http://localhost:3000/static/js/bundle.js:67209:7 div
Router#http://localhost:3000/static/js/bundle.js:67146:7
BrowserRouter#http://localhost:3000/static/js/bundle.js:65952:7
App#http://localhost:3000/static/js/bundle.js:347:82
Warning: A component is changing a controlled input to be
uncontrolled. This is likely caused by the value changing from a
defined to undefined, which should not happen. Decide between using a
controlled or uncontrolled input element for the lifetime of the
component. More info: https://reactjs.org/link/controlled-components
input SelectInput#http://localhost:3000/static/js/bundle.js:13482:19
div InputBase#http://localhost:3000/static/js/bundle.js:8257:25
WithStyles#http://localhost:3000/static/js/bundle.js:19639:25
Input#http://localhost:3000/static/js/bundle.js:9146:26
WithStyles#http://localhost:3000/static/js/bundle.js:19639:25
Select#http://localhost:3000/static/js/bundle.js:13182:26
WithStyles#http://localhost:3000/static/js/bundle.js:19639:25 div
Grid#http://localhost:3000/static/js/bundle.js:7352:29
WithStyles#http://localhost:3000/static/js/bundle.js:19639:25 div
Grid#http://localhost:3000/static/js/bundle.js:7352:29
WithStyles#http://localhost:3000/static/js/bundle.js:19639:25 form
FormProvider#http://localhost:3000/static/js/bundle.js:76722:7
AddressForm#http://localhost:3000/static/js/bundle.js:1096:7 Form div
Paper#http://localhost:3000/static/js/bundle.js:12332:17
WithStyles#http://localhost:3000/static/js/bundle.js:19639:25 main
Checkout#http://localhost:3000/static/js/bundle.js:1332:7
Routes#http://localhost:3000/static/js/bundle.js:67209:7

Related

Each child in a list should have a unique "key" prop Error [duplicate]

This question already has answers here:
Understanding unique keys for array children in React.js
(27 answers)
Closed 4 months ago.
Currently I am working on a project using React, Next.js and Ant-Design.
While working on my project, I got an error because I didn't use a unique key like this:
Below is the detailed error log.
Warning: Each child in a list should have a unique "key" prop.
Check the render method of `ForwardRef`. It was passed a child from BoardCard. See https://reactjs.org/link/warning-keys for more information.
at eval (webpack-internal:///./node_modules/antd/es/popover/index.js:30:31)
at eval (webpack-internal:///./node_modules/antd/es/card/Card.js:58:62)
at article
at BoardCard (webpack-internal:///./components/MyPage/BoardCard.js:34:19)
at li
at InternalItem (webpack-internal:///./node_modules/antd/es/list/Item.js:65:31)
at ul
at div
at div
at Spin (webpack-internal:///./node_modules/antd/es/spin/index.js:94:90)
at SpinFC (webpack-internal:///./node_modules/antd/es/spin/index.js:222:34)
at div
at List (webpack-internal:///./node_modules/antd/es/list/index.js:58:26)
at section
at BoardList (webpack-internal:///./components/MyPage/BoardList.js:22:78)
at section
at MyBoard
at section
at MyInfo
at header
at O (webpack-internal:///./node_modules/styled-components/dist/styled-components.browser.esm.js:31:19811)
at AppLayout (webpack-internal:///./components/AppLayout/index.js:28:23)
at profile
at App (webpack-internal:///./pages/_app.js:28:24)
at Provider (webpack-internal:///./node_modules/react-redux/es/components/Provider.js:13:3)
at Wrapper (webpack-internal:///./node_modules/next-redux-wrapper/es6/index.js:184:35)
at ErrorBoundary (webpack-internal:///./node_modules/next/dist/compiled/#next/react-dev-overlay/client.js:8:20746)
at ReactDevOverlay (webpack-internal:///./node_modules/next/dist/compiled/#next/react-dev-overlay/client.js:8:23395)
at Container (webpack-internal:///./node_modules/next/dist/client/index.js:241:5)
at AppContainer (webpack-internal:///./node_modules/next/dist/client/index.js:833:24)
at Root (webpack-internal:///./node_modules/next/dist/client/index.js:986:26)
As a result of checking the error log, it was confirmed that the error occurred in the Boardlist and BoardCard components.
So I checked the key of the relevant component, but I am using a unique key.
import React from 'react';
import { useSelector } from 'react-redux';
import { List } from 'antd';
import BoardCard from './BoardCard';
const BoardList = () => {
const { boardPosts } = useSelector((state) => state.user);
return (
<section>
<List
itemLayout="vertical"
bordered
size="large"
pagination={{
onChange: (page) => console.log(page), pageSize: 3,
}}
dataSource={boardPosts}
renderItem={(item) => (
<List.Item>
<BoardCard post={item} key={item.id}/>
</List.Item>
)}
/>
</section>
)
};
export default BoardList;
import React, { useState, useCallback } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { Card, Modal, Button, Popover, Row, Col, message } from 'antd';
import PropTypes from 'prop-types';
import PostModal from '../Modal/PostModal';
import PostDeleteModal from '../HomePost/PostDeleteModal';
import {
likePostRequestAction, unLikePostRequestAction,
moveToCommentRequestAction, returnToCommentRequestAction
} from '../../reducers/post';
import {
BoardCardHeader, BoardCardBody, MoreIcon, ColWrapper, CardTextWrapper,
CardTitle, CardText, CardContent, HeaderBtn, TwoToneHeartBtnIcon,
HeartBtnIcon, CommentBtnIcon, CardImageWrapper, ImageWrapper
} from './styles';
const BoardCard = ({ post }) => {
const dispatch = useDispatch();
const [visible, setVisible] = useState(false);
const id = useSelector((state) => state.user.me.id);
const liked = post.Likers.find((v) => v.id === id);
const onLikePost = useCallback(() => {
dispatch(likePostRequestAction(post.id));
}, []);
const unLikePost = useCallback(() => {
dispatch(unLikePostRequestAction(post.id));
}, []);
const showPostModal = useCallback(() => {
setVisible(true);
}, []);
const boardCardCommentBtn = useCallback(() => {
setVisible(true);
dispatch(moveToCommentRequestAction());
}, []);
const boardmodalOkBtn = useCallback(() => {
setVisible(false);
dispatch(returnToCommentRequestAction());
}, []);
const boardmodalCancelBtn = useCallback(() => {
setVisible(false);
dispatch(returnToCommentRequestAction());
}, []);
return (
<article>
<Card
headStyle={BoardCardHeader}
bodyStyle={BoardCardBody}
hoverable
extra={[
<Popover
trigger="click"
content={
<>
<Button>Modify</Button>
<PostDeleteModal post={post} />
</>
}
>
<MoreIcon key="ellipsis"/>
</Popover>
]}
>
<Row>
<ColWrapper xs={24} md={16}>
<CardTextWrapper>
<CardText
title={<CardTitle>{post.title}</CardTitle>}
description={post.desc}
onClick={showPostModal}
/>
<CardContent onClick={showPostModal}>{post.recipes}</CardContent>
</CardTextWrapper>
<div>
{
liked
? <HeaderBtn type='text' icon={<TwoToneHeartBtnIcon twoToneColor="#eb2f96" onClick={unLikePost} />}>{post.Likers.length}</HeaderBtn>
: <HeaderBtn type='text' icon={<HeartBtnIcon />} onClick={onLikePost}>{post.Likers.length}</HeaderBtn>
}
<HeaderBtn type='text' icon={<CommentBtnIcon />} onClick={boardCardCommentBtn} >{post.Comments.length}</HeaderBtn>
</div>
</ColWrapper>
<Col xs={24} md={8}>
<CardImageWrapper>
<ImageWrapper
alt="board image"
src={`http://localhost:3065/${post.Images[0]?.src}`}
onClick={showPostModal}
/>
</CardImageWrapper>
</Col>
</Row>
</Card>
<Modal
centered
visible={visible}
onOk={boardmodalOkBtn}
onCancel={boardmodalCancelBtn}
width={1000}
>
<PostModal post={post} />
</Modal>
</article>
);
};
BoardCard.propTypes = {
post: PropTypes.shape({
id: PropTypes.number,
User: PropTypes.object,
title: PropTypes.string,
desc: PropTypes.string,
content: PropTypes.arrayOf(PropTypes.object),
Images: PropTypes.arrayOf(PropTypes.object),
tag: PropTypes.string,
Comments: PropTypes.arrayOf(PropTypes.object),
})
};
export default BoardCard;
I tried to solve the problem, but couldn't find a way.
So, I would like to know why the above problem occurs and how to solve it.
You must put the key on the first child
const BoardList = () => {
const { boardPosts } = useSelector((state) => state.user);
return (
<section>
<List
itemLayout="vertical"
bordered
size="large"
pagination={{
onChange: (page) => console.log(page), pageSize: 3,
}}
dataSource={boardPosts}
renderItem={(item) => (
<List.Item key={item.id}>
<BoardCard post={item}/>
</List.Item>
)}
/>
</section>
)
};

How to change Title color when API data is active in React

I am working with a few APIs that report incidents, I have a collapse component with the titles of each upstream provider. If there's an active incident either based on an incident in the past 24 hours, or if it's in the active section, I would like to make the text in the collapse title red, otherwise make it green.
I created a new state variable called isActive, How would I go about this is React? The first is (App.js file and then Panels.js below.)
import React, { useEffect, useState } from "react";
import { Panels } from "./components/Panels";
import { BrowserRouter as Router, Routes, Route } from
"react-router-dom";
import Navbar from "./components/Navbar";
import "bootstrap/dist/css/bootstrap.min.css";
import "./App.css";
import Home from "./pages/Home";
import Team from "./pages/Team";
import Outages from "./pages/Outages";
function App() {
const emptyFeed = {
title: "",
link: "",
updated: "",
};
const [feed, setFeed] = useState(emptyFeed);
const [feedol, setFeedol] = useState(emptyFeed );
const [jsonData, setJsonData] = useState(emptyFeed);
const [azureData, setAzureData] = useState(emptyFeed);
const [isActive, setIsActive] = useState("false");
const getFeed = () => {
fetch("/feed")
.then((response) => response.json())
.then((data) => {
setFeed(data);
});
};
const getFeedOl = () => {
fetch("/feed_ol")
.then((response) => response.json())
.then((data) => {
setFeedol(data);
});
};
const getJsonData = () => {
fetch("/json_data")
.then((response) => response.json())
.then((data) => {
setJsonData(data["archive"][0]);
});
};
const getAzureData = () => {
fetch("/azure_data")
.then((response) => response.json())
.then((data) => {
setAzureData(data);
});
};
const getAllFour = () => {
getFeed();
getFeedOl();
getJsonData();
getAzureData();
};
useEffect(() => {
getAllFour();
}, []);
return (
<>
<Router>
<Navbar />
<Routes>
<Route exact path="/" element={<Home />} />
<Route path="/team" element={<Team />} />
<Route path="/outages" element={<Outages />} />
</Routes>
</Router>
<Panels
feed={feed}
feedol={feedol}
jsonData={jsonData}
azureData={azureData}
getAllFour={getAllFour}
/>
</>
);
}
export default App;
import React from "react";
import { Collapse } from "antd";
import { Card, Container } from "react-bootstrap";
import { BsArrowClockwise } from "react-icons/bs";
import "./panels.css";
import "antd/dist/antd.css";
const { Panel } = Collapse;
export const Panels = ({ feed, feedol, jsonData,
azureData,
getAllFour }) => {
return (
<Container>
<Card className="table-card">
<Card.Header>
{" "}
<button
type="button"
className=" refresh-button"
onClick={getAllFour}
>
{" "}
<BsArrowClockwise />
</button>{" "}
Upstream Outages{" "}
</Card.Header>
<Collapse accordion>
<Panel header={feedol.title} key="1">
<p>{}</p>
</Panel>
<Panel header={feed.title} key="2">
<p>{}</p>
</Panel>
<Panel header={azureData.title} key="3">
<p>{}</p>
</Panel>
<Panel header={jsonData.service_name} key="4">
<p>{}</p>
</Panel>
</Collapse>
</Card>
</Container>
);
};

react link route not redirecting to url

I have this serch.js file. When I search and click on the li in the search result, I want to get redirected to <InnerDetail /> but the URL doesn't change or I don't get redirected to this page
but manualy if I type in the URL localhost/detiled/8 I am redirected to to <InnerDetail /> with id as 8
import React from "react";
import { FontAwesomeIcon } from "#fortawesome/react-fontawesome";
import { faSearch } from "#fortawesome/free-solid-svg-icons";
import { useState, useEffect } from "react";
import axios from "axios";
import { Link } from "react-router-dom";
import { useHistory } from "react-router-dom";
const initialState = {
idaddProducts: "",
};
const Searchclients = () => {
const history = useHistory();
const [showResults, setShowResults] = React.useState(true);
const [poName, pnName] = React.useState(initialState);
const [showSerch, setShowSerch] = React.useState([]);
const [detail, setDetail] = useState(false);
const [inputValue, setInputValue] = React.useState("");
const [filteredSuggestions, setFilteredSuggestions] = React.useState([]);
const [selectedSuggestion, setSelectedSuggestion] = React.useState(0);
const [displaySuggestions, setDisplaySuggestions] = React.useState(false);
const suggestions = [];
showSerch.forEach(function (data) {
suggestions.push(data);
});
const onChange = (event) => {
const value = event.target.value;
setInputValue(value);
setShowResults(false);
const filteredSuggestions = suggestions.filter(
(suggestion) =>
suggestion.firstname
.toString()
.toLowerCase()
.includes(value.toLowerCase()) ||
suggestion.id.toString().toLowerCase().includes(value.toLowerCase())
);
setFilteredSuggestions(filteredSuggestions);
setDisplaySuggestions(true);
};
const onSelectSuggestion = (index) => {
setSelectedSuggestion(index);
setInputValue(filteredSuggestions[index]);
setFilteredSuggestions([]);
setDisplaySuggestions(false);
};
const SuggestionsList = (props) => {
// console.log(props);
const {
suggestions,
inputValue,
onSelectSuggestion,
displaySuggestions,
selectedSuggestion,
} = props;
if (inputValue && displaySuggestions) {
if (suggestions.length > 0) {
return (
<ul className="suggestions-list" style={styles.ulstyle}>
{suggestions.map((suggestion, index) => {
// console.log(suggestions);
const isSelected = selectedSuggestion === index;
const classname = `suggestion ${isSelected ? "selected" : ""}`;
return (
<Link to={`/detiled/${suggestion.id}`}> //this link dont work
<li
style={styles.listyle}
// onMouseOver={{ background: "yellow" }}
key={index}
className={classname}
>
{suggestion.firstname}
</li>
</Link>
);
})}
</ul>
);
} else {
return <div>No suggestions available...</div>;
}
}
return <></>;
};
useEffect(() => {
axios
.get("all-doctors-list/")
.then((res) => {
const data = res.data;
// pnName(data.data);
// var stringdata = data;
setShowSerch(data);
//console.log(stringdata);
});
// setShowSerch(data);
}, []);
return (
<>
<div className="note-container" style={styles.card}>
<div style={styles.inner}>
<p style={{ textAlign: "left" }}>Search Doctors</p>
<form className="search-form" style={{}}>
{showResults ? (
<FontAwesomeIcon
style={{ marginRight: "-23px" }}
icon={faSearch}
/>
) : null}
<input
onChange={onChange}
value={inputValue}
style={styles.input}
type="Search"
/>
<SuggestionsList
inputValue={inputValue}
selectedSuggestion={selectedSuggestion}
onSelectSuggestion={onSelectSuggestion}
displaySuggestions={displaySuggestions}
suggestions={filteredSuggestions}
/>
</form>
</div>
</div>
</>
);
};
export default Searchclients;
Navigator.js
import React from "react";
import { BrowserRouter as Router, Route, Switch } from "react-router-dom";
import InnerDetail from "./client/doctor/components/innerto_detail.js";
class Navigator extends React.Component {
render() {
return (
<Router>
<div>
<Switch>
<Route exact path="/">
<Home />
</Route>
<Route path="/detiled/:id">
<InnerDetail />
</Route>
</Switch>
</div>
</Router>
);
}
}
function Home() {
return (
<div style={{ paddingTop: "20%", textAlign: "center" }}>
<h1>Home</h1>
</div>
);
}
export default Navigator;
when i hover on the<li> the bottom of the browser the path is showing currectly
i think the problem is here i tried another links here nothing is working here
<Link to={`/detiled/${suggestion.id}`}> //this link dont work
<li
style={styles.listyle}
// onMouseOver={{ background: "yellow" }}
key={index}
className={classname}
>
{suggestion.firstname}
</li>
</Link>
i tryed another link under the flowing code
a button called hello and that works i think the probelm is with the return
<SuggestionsList
inputValue={inputValue}
selectedSuggestion={selectedSuggestion}
onSelectSuggestion={onSelectSuggestion}
displaySuggestions={displaySuggestions}
suggestions={filteredSuggestions}
/>
<Link
to={{
pathname: `/detiled/5`,
}}
>
<button>hello</button>
</Link>
try using
<Route path="/detiled/:id" component={InnerDetail} />
instead of
<Route path="/detiled/:id">
<InnerDetail />`
in Navigator.js
and
Route exact path="/">
<Home />
did you created any Home component, and not imported that in Navigator.js
<Link to={"/detiled/"+ suggestion.id}><li>...</li></Link>
this worked for me

React router dynamic url no redirecting me to the desired page

I want to access component according to the id of the product.
Here is my Code.
List.jsx
import { Switch, Route, Redirect, withRouter } from "react-router-dom";
import CategoryList from "./CategoryList.jsx";
import ProductList from "./ProductList.jsx";
import React from "react";
import axios from "axios";
const CategoryWithId = ({ match }) => {
console.log("Category", match.params.listId);
<ProductList listId={match.params.listId}></ProductList>;
};
function List() {
const [state, setState] = React.useState([]);
const getList = () => {
axios.get("https://api.growcify.com/dev/category/list").then((res) => {
console.log(res.data);
setState(res.data);
});
};
React.useEffect(() => {
getList();
}, []);
return (
<div className="App">
<Switch>
<Route path="/" component={() => <CategoryList state={state} />} />
<Route path="/product/:listId" component={CategoryWithId} />
<Redirect to="/" />
</Switch>
</div>
);
}
export default withRouter(List);
CategoryList.jsx
import React from "react";
import { Link } from "react-router-dom";
import Grid from "#material-ui/core/Grid";
import Paper from "#material-ui/core/Paper";
import { makeStyles } from "#material-ui/core/styles";
import { Typography } from "#material-ui/core";
const ShowCategory = (props) => {
const classes = useStyles();
const { list } = props;
return (
<Link to={`/product/${list._id}`}>
<Paper className={classes.paper} key={list._id}>
<p style={{ position: "relative", top: "40%" }}>{list.name}</p>
</Paper>
</Link>
);
};
function CategoryList(props) {
const { state } = props;
const classes = useStyles();
return (
<>
<div className={classes.header}>
<Typography variant="h3" style={{ padding: "10px" }}>
List of Categories
</Typography>
</div>
<div className={classes.container}>
<Grid container className={classes.root} spacing={2}>
<Grid item xs={12}>
<Grid container spacing={2}>
{state.map((list, index) => (
<ShowCategory list={list}></ShowCategory>
))}
</Grid>
</Grid>
</Grid>
</div>
</>
);
}
export default CategoryList;
I want that on clicking on Particular category, i should be redirect to /produce/listId.
In the url section, I can see the url with listId but I'm not getting redirected to the desired page related to that url.
Use exact keyword!
<Route exact path="/" component={() => <CategoryList state={state} />} />

Add items to Cart using React Context

I am new with React, I am trying to do the cart of the app that i am doing and I am having problems sending the items to the cart avoiding to have them duplicate or adding another extra item in the cart. These is the CartProvider code:
import { useState } from "react";
import CartContext from "./CartContext";
export const CartProvider = ({ children }) => {
const [list, setList] = useState();
const addCart = (varietals, quantity) => {
if (isInCart(varietals.item.id ) === -1){
setList(varietals)
}else{
list[isInCart].quantity += quantity
}
};
const isInCart = (id) => {
return list.findIndex(varietals => varietals.id === id)
};
return(
<>
<CartContext.Provider value={{list, addCart}}>
{children}
</CartContext.Provider>
</>);
};
This is the ItemDetail code which i use to display the Item:
import { useContext, useState } from "react";
import { Button, Container } from "react-bootstrap";
import { Link } from "react-router-dom";
import CartContext from "../../Context/CartContext";
import Item from "../Item/Item";
import ItemCountComponent from "../ItemCount";
const ItemDetail = ({ varietals }) => {
const [checkout, setCheckout] = useState(false);
const { list, addCart } = useContext(CartContext);
const onAdd = (count) => {
console.log("Selected ", count);
setCheckout(true);
addCart({Item: varietals, Quantity: count});
};
console.log(list)
return (
<>
<br />
<Container className="py-5 px-5 shadow">
<Item varietals={varietals} />
<div className="ml-4 mr-3">
<div className="font-italic mb-4 text-center text-muted">{varietals.description}</div>
{checkout ? <Link to='/Cart'><Button variant="info">Checkout</Button></Link> : <ItemCountComponent className="d-flex justify-content-center" onAdd={onAdd} stock={5} initial={1} />}
</div>
</Container>
</>
)
};
export default ItemDetail;
This is the Item.jsx:
import { Card, Container } from "react-bootstrap";
import "./Style.scss";
const Item = ({ varietals }) => {
return (
<>
<Container className="px-1">
<Card className="clemmy">
<Card.Img variant="top" src={varietals.pictureUrl} className="shadow"/>
<Card.Body>
<Card.Title className="d-flex justify-content-center text-muted">
{varietals.title}
</Card.Title>
<Card.Subtitle className="d-flex justify-content-center text-muted">
${varietals.price}
</Card.Subtitle>
</Card.Body>
</Card>
</Container>
</>
)
};
export default Item;
This is the ItemListContainer.jsx:
import { useEffect, useState } from "react";
import { useParams } from "react-router-dom";
import aimara from "../../aimara";
import ItemList from "../../Components/ItemList/ItemList";
const ItemListContainer = () => {
const [varietals, setVarietals] = useState([])
const { categoryId } = useParams();
useEffect(() => {
const myPromise = new Promise((resolve, reject) => {
if (categoryId) {
const products = aimara.filter((producto) => {
return producto.category.toString() === categoryId;
});
resolve(products);
} else resolve(aimara);
});
myPromise.then((result) => setVarietals(result));
}, [categoryId]);
return <ItemList varietals={varietals} />
};
export default ItemListContainer;
The error that I am seeing is "TypeError: Cannot read property 'id' of undefined"
If there is someone that could help me would be much appreciate it. Also, in case you need some extra file let me know and I update the post as quickly as I can. Cheers

Categories

Resources