Working on a shopping cart project that has two main pages: The video game page that shows a bunch of video games (stored as objects inside an array and mapped to the screen) and a shopping cart page that displays a list of any game with an inCart value set to true. The default value of every game is false. In order to set the value to true the user simply clicks "Add to Cart" from the video game page.
I've spent the past several hours trying to figure out why my code isn't working properly.
VideoGameList is the name of my array that is holding the object data.
const VideoGameList = [
{
id: 1,
title: "Fire Emblem Engage",
inCart: false,
},
];
VideoGame.js
// VideoGameList is the name of array holding video game values
const [cart, setCart] = useState(VideoGameList);
// Changes Boolean values from false to true
const handleCartStatus = (id) =>
setCart(
cart.map((value) =>
value.id !== id ? value : { ...value, inCart: !value.inCart }
)
);
I'm mapping the data to display on screen which shows each game in its own nice div and included a button and when the user clicks the button it calls the handleCartStatus function to change the Boolean value of inCart from false to true. However, in order to display the most recent values, I can't use VideoGameList.map I have to use cart.map as that is what state is changing each time I click "Add to Cart".
<ShoppingCart cart={cart} /> // sends props of cart to ShoppingCart component
{cart.map(({ id, title }, index) => (
<div>
<img key={src} src={src} alt={title} />
<div>
<p>{title}</p>
</div>
<div>
<button
onClick={() => handleCartStatus(id)}
>
Add to Cart
</button>
</div>
</div>
))}
Because I need access to cart.some and cart.filter in another component I'm sending the props to my third component which is the actual ShoppingCart page. When I was using VideoGameList.map it was only showing the unchanged values so nothing was ever displayed on screen.
This page displays a div of every object that has its inCart value set to true.
ShoppingCart.js
const ShoppingCart = (props) => {
return (
<>
{props.cart?.some((v) => v.inCart) ? (
<div>
{props.cart
?.filter((v) => v.inCart)
?.map(({ title }, index) => (
<div>
</div>
))}
</div>
Here's where I need help
I know using ShoppingCart cart={cart} /> inside my VideoGame component is causing the ShoppingCart to display in my VideoGame component but how else am I supposed to send the props of cart? I should also mention I have <Header /> displayed in each component and it's now showing up twice on my VideoGame page, one from my VideoGame component and the other from my ShoppingCart component. Furthermore, I don't understand why using props.cart?.some inside of my ShoppingCart component isn't working at all and is showing a blank screen. It's essentially giving me unidentified values despite working in my VideoGame page.
Related
I'm creating a video game shopping cart.
I have a component that is storing data of recent video games.
VideoGameList.js
const VideoGameList = [
{
id: 1,
title: "Fire Emblem Engage",
inCart: false,
},
];
And another component that displays the objects in their own div. Inside that component I have this code which takes the VideoGameList array and sets a new array upon clicking "Add to Cart" and changes the inCart value from false to true.
VideoGame.js
const [cart, setCart] = useState(VideoGameList);
const handleCartStatus = (id) =>
setCart(
cart.map((value) =>
value.id !== id ? value : { ...value, inCart: !value.inCart }
)
);
I then have to map through the new array like so
{cart.map(
({ id, title, inCart }, index) => (
<div>
<img key={src} src={src} alt={title} />
<div>
<p>{title}</p>
<p>{releaseDate}</p>
</div>
<div>
<p>${price}</p>
<button
onClick={() => handleCartStatus(id)}
>
Add to Cart
</button>
Here's my problem
I have a third component which is the actual ShoppingCart page. Originally when I made this component I was using this code
ShoppingCart.js
const ShoppingCart = () => {
return (
<>
<Header />
{VideoGameList.some((v) => v.inCart) ? (
<div>
{VideoGameList.filter((v) => v.inCart).map(
(
{ id, title, inCart },
index
) => (
<div>
<img key={src} src={src} alt={title} />
<div>
<p>{title}</p>
<p>{releaseDate}</p>
</div>
<div>
<p>${price}</p>
<button>Add to Cart</button>
</div>
</div>
)
)}
</div>
) : (
<div>
<h1>Your Shopping Cart Is Empty!</h1>;
<div className="shopping-cart-image">
</div>
</div>
)}
</>
);
};
The code works in one of two ways. Either the user has an empty shopping cart and an image + some text is displayed or they have a minimum of one item in their shopping cart and a div of said item (video game) was displayed. An item is considered in their shopping cart when the inCart value is set to true. I was basing the some and filter methods on the VideoGameList array and was manually changing the inCart values to true to see if it worked (it did) however, because I have to change state from the VideoGame component I have to change VideoGameList.some and VideoGameList.filter to cart.some and cart.filter to get the updated inCart values but every time I change it I get this error.
src\Components\ShoppingCart.js
Line 11:8: 'cart' is not defined no-undef
Line 13:12: 'cart' is not defined no-undef
If I continue using VideoGameList it will never update the Shopping Cart but I can't find a way to use cart from my VideoGame component inside my ShoppingCart component. Please advice.
I have a set of movie cards coming from an API. When I click on the movie a modal opens with a button in it. Since there is a lot of movies, I would like to know which button was clicked on, to preserve that button's state as
'Added to Watchlist', if it was clicked on. How could I achieve that?
Pass a movie name/movie ID as a prop to the button. Id can be stored as a state in the parent component.
//movieCard is API response
state = {
movideId: '',
isOpneModal: false,
}
openModal = (cardId) => setState({ movideId: cardId })
render() {
return (
<Fragment>
{movieCard.map(card =>
<MovieCard cardDetails={card} onClick="()=>openModal(card.Id)") />
)}
{isOpneModal && <Modal movideId={this.state.movideId} />}
</Fragment>
)
I'm trying to complete my first big assignment for school where I need to use react-router and redux. I'm at the last page/component but have been completely stuck for the past 2 days. The app is an app to order coffee. I have a menu page/component, to which I added my menu items with a .map of a json file for an 'items' component. I now need to be able to add my items onClick to the cart component but I can't figure out how.
I had thought of maybe saving either the whole needed data of the item to an empty array, which then I would push to my cart component and then map all the info for a new component to generate the cart items. But after 2 days of failed attempts, I just now managed within the 'items' component to create a 'inCart' state that saves an array with the 2 pieces of info I need for my cart.
There still are 2 issues though:
on the first click nothing gets saved, but its only after the second click that the items show up in my array.
because the state is created within the 'items' component which then is mapped, my state is also connected to only one item at a time, so if I click on 2 different types of coffee, these won't end up in the same array.
I get the feeling that maybe redux would be the way to go in this case, but as I'm very new at it, I can't quite wrap my head around how that would be implemented in this case.
Overall what I find is making it hard for me to find a solution is the fact that the button I need my onClick function to work with is inside the 'items' component while I would need a state with my array to be in my 'menu' component, in order to record all different types of coffee chosen. That's why I'm thinking Redux would maybe be the solution, but not sure how to implement it.
Any types of suggestions that would put me in the right direction to get this problem solved are warmly welcome!!
Following are my 'menu' component and 'item' component code to clarify where I'm at right now.
MENU COMPONENT:
const Menu = () => {
let items = require('../assets/menu.json');
let counter = useSelector(state => state.cartCounter);
const dispatch = useDispatch();
const showNav = useSelector(state => state.toggleNav);
const showCart = useSelector(state => state.toggleCart);
if (showNav){
return ( <Nav /> )
} else {
return (
<section className='menu'>
{showCart ? <Cart /> : ''}
<header>
<section className='nav' onClick={() => dispatch(toggleNav())}>
<div ></div>
<div></div>
<div></div>
</section>
<section onClick={() => dispatch(toggleCart())}>
<img src={bag} alt='bag' className='bag'></img>
<p className='cart-counter'>{counter}</p>
</section>
</header>
<h1>Meny</h1>
{items.map((item, index) => <Item key={index} data={item}/>)}
</section>
)}
}
export default Menu;
ITEM COMPONENT:
const Item = (props) => {
const dispatch = useDispatch();
let [inCart, setInCart] = useState([]);
const updateInCart= (e) => {
setInCart([
...inCart,
{
title: props.data.title,
price: props.data.price,
}
]);
};
const onClick = (e) => {
dispatch(cartIncrement());
updateInCart();
console.log(inCart)
}
return (
<section className='item-container'>
<img src={add} alt='add' className='add-cart' onClick={onClick}></img>
<article className='item-text'>
<section className='first-line'>
<h2 >{props.data.title}</h2>
<h2 className='price'>{props.data.price} kr</h2>
</section>
<p className='beans'>{props.data.beans}</p>
</article>
</section>
);
}
export default Item;
I have an array of Json objects('filteredUsers' in below code) and I'm mapping them to a html table. Json object would look like {id: xyz, name: Dubov}
The below code would display a html table with a single column or basically a list. Each row will have name of user and a grey checkbox(unchecked) next to it initially. I want to select users in the table and when I select or click on any item in table, the checkmark has to turn green(checked).
<table className="table table-sm">
{this.state.filteredUsers && (
<tbody>
{this.state.filteredUsers.map((user) => (
<tr key={user.id}>
<td onClick={() => this.selectUser(user)}>
<span>{user.name}</span> //Name
<div className={user.selected? "checked-icon": "unchecked-icon"}> //Checkmark icon
<span class="checkmark"> </span>
</div>
</td>
</tr>
))}
</tbody>
)}
</table>
I tried setting a 'selected' key to each object. Initially object doesn't have 'selected' key so it will be false(all unchecked). I set onClick method for 'td' row which sets 'selected' key to object and sets it to true. Below function is called onClick of td or table item.
selectUser = (user) => {
user.selected = !user.selected;
};
Now the issue is this will only work if I re-render the page after every onClick of 'td' or table item. And I'm forced to do an empty setState or this.forcedUpdate() in selectUser method to trigger a re-render. I read in multiple answers that a forced re-render is bad.
Any suggestions or help would be highly appreciated. Even a complete change of logic is also fine. My end goal is if I select an item, the grey checkmark has to turn green(checked) and if I click on it again it should turn grey(unchecked). Similarly for all items. Leave the CSS part to me, but help me with the logic. Thanks.
How about something like this:
const Users = () => {
const [users, setUsers] = useState([])
useEffect(() => {
// Fetch users from the API when the component mounts
api.getUsers().then((users) => {
// Add a `selected` field to each user and store them in state
setUsers(users.map((user) => ({ ...user, selected: true })))
})
}, [])
const toggleUserSelected = (id) => {
setUsers((oldUsers) =>
oldUsers.map((user) =>
user.id === id ? { ...user, selected: !user.selected } : user
)
)
}
return (
<ul>
{users.map((user) => (
<li key={user.id} onClick={() => toggleUserSelected(user.id)}>
<span>{user.name}</span>
<div className={user.selected ? "checked-icon" : "unchecked-icon"}>
<span class="checkmark" />
</div>
</li>
))}
</ul>
)
}
I've used hooks for this but the principles are the same.
This looks to be a state issue. When updating data in your react component, you'll need to make sure it's happening in one of two ways:
The data is updated by a component higher up in the tree and then is passed to this component via props.
this will cause your component to re-render with the new props and data, updating the "checked" property in your HTML.
In your case, it looks like you're using this second way:
The data is stored in component state. Then, when you need to update the data, you'd do something like the below.
const targetUser = this.state.filteredUsers.find(user => user.id === targetId)
const updatedUser = { ...targetUser, selected: !targetUser.selected }
this.setState({ filteredUsers: [ ...this.state.filteredUsers, updatedUser ] })
Updating your state in this way will trigger an update to your component. Directly modifying the state object without using setState does not trigger the update.
Please keep in mind that, when updating objects in component state, you'll need to pass a new, full object to setState in order to trigger the update. Something like this will not work: this.setState({ filteredUsers[1].selected: false });
Relevant documentation
I am building a recipe app that allows a user to add custom recipes and then display them.
I am able to add one recipe just fine, but when I add a second recipe, it changes the first one to have the same data as the second.
The initial state of the list of recipes is set as an empty array:
recipeList: [],
newRecipe: {
title: '',
source: '',
id: ''
Every time I hit a submit Recipe button, I want to be able to add a new recipe to the array and display it as a thumbnail (see screenshot above). The new recipe is in the form of an object, and as seen above, the initial state of the new recipe object is set to empty. So essentially I want to be able to put new user input into the new recipe object, add it to the empty array, and display the entire array as recipe thumbnails.
In the React Dev Tools, I see both recipes in the array, so I know they are being added. But for some reason they are not being displayed correctly.
Upon submission, each item in the array is mapped over and returned as a thumbnail:
return (
<div className="App">
<Navbar />
<div className='app-body'>
{this.state.recipeList.map((recipe) => (
<RecipeCardThumbnail
key={this.state.id}
title={this.state.title}
source={this.state.source}
/>
))}
So it could be a problem with the map() method as it seems it is not mapping through the correct array.
This is the function that fires when I submit a form to add a new recipe:
handleSubmitNewRecipe = e => {
e.preventDefault();
this.handleAddNewRecipe(this.state.title, this.state.source, this.state.id);
};
And here's the function for adding a new recipe:
handleAddNewRecipe = (title, source) => {
const newRecipe = {
title: title,
source: source,
id: (Math.floor(Math.random()* 1000))
}
this.setState({recipeList: [...this.state.recipeList, newRecipe] });
console.log(this.state.recipeList)
};
When the array is mapped over, it returns a component called<RecipeCardThumbnail />. Here is the code for that component:
return (
<div className="card select thumbnail-card">
<div className="card-body">
<h5 className="card-title">{this.props.title}</h5>
<h6 className='card-subtitle text-muted'>{this.props.source}</h6>
<ul className="qty-details">
<li >{this.props.servings}</li>
<li >{this.props.prepTime}</li>
<li >{this.props.cookTime}</li>
<li >{this.props.totalTime}</li>
</ul>
</div>
</div>
);
In addition to each item not being displayed, I also get an error saying that each child needs a unique key. I thought that the id that I have works as a key.
Not sure if this is enough code, but you can view the entire code here: Recipe App on Github
At a glance it seems you should be using properties of recipe here, not this.state.
So this:
{this.state.recipeList.map((recipe) => (
<RecipeCardThumbnail
key={recipe.id}
title={recipe.title}
source={recipe.source}
/>
))}
Instead of this:
{this.state.recipeList.map((recipe) => (
<RecipeCardThumbnail
key={this.state.id}
title={this.state.title}
source={this.state.source}
/>
))}