shopping site in NextJS - can't figure out how to send the card from shop/page.jsx, to cart/page.jsx

https://github.com/callum-laing/shopping-site/tree/main Starting off simple, though I'm not sure how I do this (first time trying). I need "add to cart" to send the card that I'm clicking over to cart/page.jsx and display the card on that page.
GitHub
GitHub - callum-laing/shopping-site: Created in NextJS/React
Created in NextJS/React. Contribute to callum-laing/shopping-site development by creating an account on GitHub.
140 Replies
b1mind
b1mindā€¢8mo ago
You would either send it with a form use the formApi to POST on the BE and store it. Then display it in the cart Or you could use a searchParam and send it in the url then based on the search you send do something to get the proper item. Or use local storage to save them get again (this would be browser/client side only though)
CDL
CDLā€¢8mo ago
oh jeez, I'll look into this tomororw, thanks mate Is it me, or is this quite a complex thing to achieve? I just asked chatgpt to give me an example, it's written like 200 lines of code on 4 different pages lmao.
b1mind
b1mindā€¢8mo ago
I mean depends, I don't know what's NextJS it React are doing to get in the way. But no sending a form has been around since the test of time. So have searchParams
CDL
CDLā€¢8mo ago
It's the last front-end project from TOP so using BE is cheating there, so I can't use it
b1mind
b1mindā€¢8mo ago
Local storage is nice but yea you can't see it on a server.
CDL
CDLā€¢8mo ago
has to be FE only
b1mind
b1mindā€¢8mo ago
Huh šŸ˜‚
CDL
CDLā€¢8mo ago
am I wrong? šŸ˜„
b1mind
b1mindā€¢8mo ago
Wrong for what? I don't know your lesson plan Link it? Those are the three ways to send data šŸ˜„ I'm not sure what special things you have to do around NextJS though
b1mind
b1mindā€¢8mo ago
Stack Overflow
how to pass data from one page to another page in Next.js?
I am stuck with a problem with passing data from one page to another page in next.js as I am building a basic news application in which I am fetching get requests from news api and I got results of...
b1mind
b1mindā€¢8mo ago
lol first search in SO tells you the same thing xD I'm not sure if NextJS has a good answer for real forms that is one the reasons I would prefer Remix if I had to use a router for React. Astro has an "ok" solution but no progressive enhancement (JS client side spice)
CDL
CDLā€¢8mo ago
sorry was watching a last of the mohicans clip lol
b1mind
b1mindā€¢8mo ago
I would think you can access the formAPI with a RSC but I don't see it off a quick search.
CDL
CDLā€¢8mo ago
so the plan is literally just build a shopping cart like i have done without the cart part
b1mind
b1mindā€¢8mo ago
fail
CDL
CDLā€¢8mo ago
Project: Shopping Cart | The Odin Project
The Odin Project empowers aspiring web developers to learn together for free
b1mind
b1mindā€¢8mo ago
At the very least you should do a simple localStorage state
CDL
CDLā€¢8mo ago
sorry I meant it requires the cart, but i haven't done that yet
b1mind
b1mindā€¢8mo ago
oh don't turn it in I'll fail ya <,<;; šŸ¤£
CDL
CDLā€¢8mo ago
all im missing on MY app is adding functionality so when I click the "add to cart" button, it adds that card to my cart page so i can view it in a basket container or w.e but yeah ive no idea how to do it even googling and watching youtube, i cant figure this shit out lol im braindead on frameworks rn
b1mind
b1mindā€¢8mo ago
I just told you this isn't frameworks this is how the web works searchParams are a common way to pass state using the URL (url === best state) So you would have a link for the item to like /cart?id=13241234
CDL
CDLā€¢8mo ago
oh, hmm
b1mind
b1mindā€¢8mo ago
and use searchParam method on the that page to get the id
CDL
CDLā€¢8mo ago
yeah nextjs is the "issue", havent a clue on the fucking thing forthe most part, nothing seems teh same as react
b1mind
b1mindā€¢8mo ago
then you can get just that id from yoru dataset that is because just React sux bawls
CDL
CDLā€¢8mo ago
even litle things like = useState() is actually = React.useState() -.-
b1mind
b1mindā€¢8mo ago
React query is not a good router lol but you have to understand what those are that has nothing to do with this Make sure you are understanding this stuff and what it is Like React alone does not have multiple pages Most old react is one page of šŸ¤¢ Just changing your URL does not make it multiple pages šŸ˜„ (even then that is a form of URL=state) having muliple pages makes it MPA šŸ˜‚ aka OLD CRApp is bad NEXTjs and Remix are good that SO post shows you exactly how to do it in NextJS btw Other option* you probably have access to in Next is [id]/page.jsx routes so if the folder was lik cart/[id]/page.jsx then that page should get a param of id and what ever you give it. but yea idk mate šŸ˜„ URL = best state learn it well and use it. but you will need away to store the items in the cart still too xD typically where you would be getting it on the server and saving to a db so just use local storage in that way
CDL
CDLā€¢8mo ago
TOP admins shouted at me for using next šŸ˜¦ bullies i think they use CRA still, which I thought was bsically redundant now
b1mind
b1mindā€¢8mo ago
yea f' CRApp Not like you have to turn this shit in right? You do you Also it wouldn't matter The issue is still the same issue (again this is a web platform thing not a Framework thing) Just a worst one in CRApp šŸ¤£ I guess in CRApp though you would never have to change pages but you still have to pass the data, you still have to store the data, you still have to recieve the stored data based on keys you passed from the item to know which item keys/ids w/e you wanna call it I would not recommend doing words or titles as index/ids are much more reliable. I have a site that uses titles and I regret it šŸ¤£ (on a todo to change it lol) Worst in React only* is what you going to use Redux? šŸ¤£ they don't give you gobal state out of the box šŸ¤” TOP admins dumb they just want you to follow the lesson cause its what they know. (which isnt wrong I wouldn't support something else either, this is you on your own, but you are doing it the better way period) šŸ˜‚
CDL
CDLā€¢8mo ago
wait wtf, there's no way it's that simple. unless I'm really really oversimplifying this answer (I can't react to everything you just wrote, ebcause you went off on a tangent) so here's an emoji šŸ§™ā€ā™‚ļø šŸ¤£
b1mind
b1mindā€¢8mo ago
I mean yes then you just have to store it.
CDL
CDLā€¢8mo ago
This guy seems like he knows what he's doing https://www.youtube.com/watch?v=LcaqzH6-XkY
b1mind
b1mindā€¢8mo ago
nope stop trying to use context xD I mean do what ever ig just get it done šŸ˜‚ This is not teh way though, it would lose it all on a page refresh faik
CDL
CDLā€¢8mo ago
I'm trying to figure out why no-one is doing it the way you're suggesting are you just a weirdo, or are you a gigachad
b1mind
b1mindā€¢8mo ago
mate... I'm telling you its how the web works EVERYONE DOES IT BUT REACT BRAIN PEOPLE
CDL
CDLā€¢8mo ago
šŸ¤£
b1mind
b1mindā€¢8mo ago
cause they have fucking react brain NextJS is a MPA framework now I gave you the answer in the SO poast
CDL
CDLā€¢8mo ago
so you're saying all i need is searchParam to do this
b1mind
b1mindā€¢8mo ago
you just need to reference your data and save the item that is in the card to a db no I'm saying that is how you pass info from one page to another without a POST request
CDL
CDLā€¢8mo ago
ah
b1mind
b1mindā€¢8mo ago
which is going to be easiest for you If I was doing this today I'd do it in a proper form method="POST" and handle the post on the back end. but you don't always need to do it like that or with addition you want to send a param/searchParam
CDL
CDLā€¢8mo ago
This iswhat you're on about yeah
No description
b1mind
b1mindā€¢8mo ago
you do that with dynmaic routes [id] or ?id=313421 in the URL
CDL
CDLā€¢8mo ago
I get what you're on about
b1mind
b1mindā€¢8mo ago
then you use that id on the next page to reference the ID in your dataset then you pull that data from the set and save it somehow then reference it when the page is load if it has that or not "in the cart" start looking at real website you will see searchParams EVERYWHERE google search for one šŸ˜‚
CDL
CDLā€¢8mo ago
I get what you're saying bud, I'm just trying to figure out how I implement it into my code, that's where my issues arise not with what you're explaining šŸ˜›
b1mind
b1mindā€¢8mo ago
you just pasted a screenshot of how dead simple really, the Link component takes a query string you give it an id.. then on the cart page you get that id. A Global store makes sense but only if the client side never fails or page never is refreshed. At that point I'd just use localStorage for it all
const Shop = () => {
return (
<main className={Styles.shopContainer}>
{posts.map((post) => (
<div key={post.id} className={Styles.card}>
<Image
className="imgCard"
src={post.image}
alt={post.name}
width={450}
height={600}
sizes="100vw"
/>
<h2>{post.name}</h2>
<p>Price: ${post.price}</p>
<Link
href={{
pathname: '/cart',
query: {
id: post.id
}
}}
>
Add to cart
</Link>
</div>
))}
</main>
);
};
const Shop = () => {
return (
<main className={Styles.shopContainer}>
{posts.map((post) => (
<div key={post.id} className={Styles.card}>
<Image
className="imgCard"
src={post.image}
alt={post.name}
width={450}
height={600}
sizes="100vw"
/>
<h2>{post.name}</h2>
<p>Price: ${post.price}</p>
<Link
href={{
pathname: '/cart',
query: {
id: post.id
}
}}
>
Add to cart
</Link>
</div>
))}
</main>
);
};
make sure you import link Then if you are going to use a Client side solution like LocalStorage (otherwise you need to use a RSC and sqlite or some db)
'use client'

import { useSearchParams } from 'next/navigation'

const Cart = () => {
const searchParams = useSearchParams()
console.log(searchParams.get('id')) // Logs post.id value from url
const id = searchParams.get('id')
const item = posts.fitler(post => post.id !== id)

//... save item to localStorage or something
}

export default Cart
'use client'

import { useSearchParams } from 'next/navigation'

const Cart = () => {
const searchParams = useSearchParams()
console.log(searchParams.get('id')) // Logs post.id value from url
const id = searchParams.get('id')
const item = posts.fitler(post => post.id !== id)

//... save item to localStorage or something
}

export default Cart
something like that ya? damn it editing in discord and I hit esc šŸ¤£
CDL
CDLā€¢8mo ago
sorry was grabbing my dinner, let me catch up reading
b1mind
b1mindā€¢8mo ago
np I should eat too lunch time here.
CDL
CDLā€¢8mo ago
are those 2 snippets the same "set"? or is that 2 different variations of how to do this oh, they work together
b1mind
b1mindā€¢8mo ago
those are your two pages
CDL
CDLā€¢8mo ago
that's all I need...?
b1mind
b1mindā€¢8mo ago
I mean you have to render to the page or w/e on Cart but yea that would get you the item I think try it
CDL
CDLā€¢8mo ago
ah ok so this you can maybe explain
CDL
CDLā€¢8mo ago
No description
CDL
CDLā€¢8mo ago
It's literally just 'use client' at the top?
b1mind
b1mindā€¢8mo ago
yes that string has to be first at the top of your file faik or you can do the back end one
CDL
CDLā€¢8mo ago
should it be post.filter?
b1mind
b1mindā€¢8mo ago
no you need to filter from your array
CDL
CDLā€¢8mo ago
No description
b1mind
b1mindā€¢8mo ago
did you import it?
CDL
CDLā€¢8mo ago
fucking imports man.. yeah i have now
b1mind
b1mindā€¢8mo ago
gotta have em lol
CDL
CDLā€¢8mo ago
that's weird. my button has uhh.. vanished, it's just a text now, and when you click add to cart, it just goes into a white screen
b1mind
b1mindā€¢8mo ago
necessary evil ig šŸ˜‚ did you import Link? also it will be a link not a button
CDL
CDLā€¢8mo ago
that'll be because of Link yeah
b1mind
b1mindā€¢8mo ago
you can just add your styles to it
CDL
CDLā€¢8mo ago
that's fine I need to test why it's just white screening me then
b1mind
b1mindā€¢8mo ago
because you don't have your render? you need to keep your render or maybe not idk lol this is where my know how is limited do this
//cart.jsx
import React from "react";

export default function Cart({searchParams}) {
return (
<div>
<h2>Please proceed to give me your card details!</h2>
{searchParams.id}
</div>
);
//cart.jsx
import React from "react";

export default function Cart({searchParams}) {
return (
<div>
<h2>Please proceed to give me your card details!</h2>
{searchParams.id}
</div>
);
CDL
CDLā€¢8mo ago
it does change to http://localhost:3000/cart?id=2 when you click
b1mind
b1mindā€¢8mo ago
yea yea that part works I know its the cart component we need to fix
CDL
CDLā€¢8mo ago
ah I mean, there's nothing in here atm right
b1mind
b1mindā€¢8mo ago
You are teaching me next šŸ¤£
CDL
CDLā€¢8mo ago
just logic
b1mind
b1mindā€¢8mo ago
clear the client only code and try this real fast. (comment it out or w/e) I mean both those should work šŸ¤” the 'use client' would still be returning Card
CDL
CDLā€¢8mo ago
same result
b1mind
b1mindā€¢8mo ago
did your cart page ever work? like render the h2
CDL
CDLā€¢8mo ago
yeah it would show the html wait am i keeping any of the previous code?
b1mind
b1mindā€¢8mo ago
no
CDL
CDLā€¢8mo ago
"use client";

import { useSearchParams } from "next/navigation";
import posts from "../data";

export default function Cart({ useSearchParams }) {
return (
<div>
<h2>Please proceed to give me your card details!</h2>
{searchParams.id}
</div>
);
}
// const Cart = () => {
// const searchParams = useSearchParams();
// console.log(searchParams.get("id")); // Logs post.id value from url
// const id = searchParams.get("id");
// const item = posts.filter((post) => post.id !== id);

// //... save item to localStorage or something
// };

// export default Cart;
"use client";

import { useSearchParams } from "next/navigation";
import posts from "../data";

export default function Cart({ useSearchParams }) {
return (
<div>
<h2>Please proceed to give me your card details!</h2>
{searchParams.id}
</div>
);
}
// const Cart = () => {
// const searchParams = useSearchParams();
// console.log(searchParams.get("id")); // Logs post.id value from url
// const id = searchParams.get("id");
// const item = posts.filter((post) => post.id !== id);

// //... save item to localStorage or something
// };

// export default Cart;
b1mind
b1mindā€¢8mo ago
you have to export ya dork
CDL
CDLā€¢8mo ago
it's exporting "export default function"
b1mind
b1mindā€¢8mo ago
that is not the 'use client' oh wait ya comment out 'use client' sorry I had them mixed up xD
CDL
CDLā€¢8mo ago
np i need to keep the searchParams const in there though don't I
b1mind
b1mindā€¢8mo ago
that is correct but you comment out client code you need to comment out the use string yes test from the link or you could put {searchParams?.id || 'blank'} maybe but if it trys now to get it probably fails cause ya if its not in the url
CDL
CDLā€¢8mo ago
bare with me 1 sec, im not combining those 2 code blocks, im just commenting out use client?
import { useSearchParams } from "next/navigation";
import posts from "../data";

export default function Cart({ useSearchParams }) {
const searchParams = useSearchParams();
console.log(searchParams.get("id")); // Logs post.id value from url
const id = searchParams.get("id");
const item = posts.filter((post) => post.id !== id);
return (
<div>
<h2>Please proceed to give me your card details!</h2>
{searchParams.id}
</div>
);
import { useSearchParams } from "next/navigation";
import posts from "../data";

export default function Cart({ useSearchParams }) {
const searchParams = useSearchParams();
console.log(searchParams.get("id")); // Logs post.id value from url
const id = searchParams.get("id");
const item = posts.filter((post) => post.id !== id);
return (
<div>
<h2>Please proceed to give me your card details!</h2>
{searchParams.id}
</div>
);
this is not what you're asking is it
b1mind
b1mindā€¢8mo ago
ya that looks right err no don't need the import useSearch I'm trying to think how I can help you understand more of what you are doing cause that is telling kinda
CDL
CDLā€¢8mo ago
I mean atm it's just breaking on several things, useSearchParam() isn't a function, then it can't read the properties of .get
b1mind
b1mindā€¢8mo ago
you don't need the import ya you like combined the things no clue why šŸ˜‚ so remove line 1 and 5 you are getting the param from the route Cart({useSearchParam})
CDL
CDLā€¢8mo ago
WAIT WE HAVE SOMETHING
b1mind
b1mindā€¢8mo ago
muhahah getting there!
CDL
CDLā€¢8mo ago
No description
b1mind
b1mindā€¢8mo ago
winning!!!
CDL
CDLā€¢8mo ago
oh shit
b1mind
b1mindā€¢8mo ago
Ok so you understand what is going on though? that is most important This is "serverside" I think in next so you have to handle it as such
CDL
CDLā€¢8mo ago
so we added Link to shop and added searchParams to cart
b1mind
b1mindā€¢8mo ago
we send the id of the post.id using the Link yes in a searchParam to the url, the Cart then looks at the searchParams in the URL and gives you the value.
CDL
CDLā€¢8mo ago
and when you click on the link, its posting that id to the cart
b1mind
b1mindā€¢8mo ago
yup
CDL
CDLā€¢8mo ago
ok I like that
b1mind
b1mindā€¢8mo ago
Like right now put any number in your URL
CDL
CDLā€¢8mo ago
that's wayyyyy less code than context
b1mind
b1mindā€¢8mo ago
42069 and it should render that number on the page
CDL
CDLā€¢8mo ago
yeah it renders
b1mind
b1mindā€¢8mo ago
So that is the most basic and core way to pass info on the web
CDL
CDLā€¢8mo ago
yeah now that I see it working, and I see the code, it's very simple I just couldn't comprehend how it looks in my head
b1mind
b1mindā€¢8mo ago
The draw backs are you don't get to add to cart from the shop page cause you have to navigate to the cart page. but that is a UX choice lots of places do it right?
CDL
CDLā€¢8mo ago
if you go to shop and come back to cart, it does vanish though
b1mind
b1mindā€¢8mo ago
yes and do you know why?
CDL
CDLā€¢8mo ago
well i dont think im saving it anywhere am i?
b1mind
b1mindā€¢8mo ago
correct! but real fast before you do that we need more than the id right?
CDL
CDLā€¢8mo ago
yep i need the lot
b1mind
b1mindā€¢8mo ago
return (
<div>
<h2>Please proceed to give me your card details!</h2>
<p>
{item[0].id}
{item[0].name}
{item[0].price}
{item[0].image}</p>

</div>
);
return (
<div>
<h2>Please proceed to give me your card details!</h2>
<p>
{item[0].id}
{item[0].name}
{item[0].price}
{item[0].image}</p>

</div>
);
lets make sure you have data sry I'm not formatting šŸ˜‚ So you should have item if its posts.filter() is right. should be removing anything that does not match id
CDL
CDLā€¢8mo ago
where'd your posts.filter come from
b1mind
b1mindā€¢8mo ago
o but its in an array probably šŸ¤” item[0] maybe this is where I need working code myself its so hard just in my head yea cause it would be returning an array still
CDL
CDLā€¢8mo ago
it's not finding item atm, need to solve that bit then i can look at the array
b1mind
b1mindā€¢8mo ago
console.log(item) before the return if its an array of one šŸ˜‚
CDL
CDLā€¢8mo ago
No description
b1mind
b1mindā€¢8mo ago
where is your logic I feel like I'm just giving you code and your not grasping what steps you need šŸ˜¦
const id = searchParams.get("id");
const item = posts.filter((post) => post.id !== id);
const id = searchParams.get("id");
const item = posts.filter((post) => post.id !== id);
CDL
CDLā€¢8mo ago
I was following until you mentioned filter and then I got a littel confused
b1mind
b1mindā€¢8mo ago
ya cause you removed it from the org code I sent ya again I can only go of what I've given you, and assume its what you have
CDL
CDLā€¢8mo ago
ok so I have this right now, I've just copied the logic into the top
import React from "react";

export default function Cart({ searchParams }) {
const searchParams = useSearchParams();
console.log(searchParams.get("id")); // Logs post.id value from url
const id = searchParams.get("id");
const item = posts.filter((post) => post.id !== id);
console.log(item);

return (
<div>
<h2>Please proceed to give me your card details!</h2>
<p>
{item[0].id}
{item[0].name}
{item[0].price}
{item[0].image}
</p>
{searchParams.id}
</div>
);
}
import React from "react";

export default function Cart({ searchParams }) {
const searchParams = useSearchParams();
console.log(searchParams.get("id")); // Logs post.id value from url
const id = searchParams.get("id");
const item = posts.filter((post) => post.id !== id);
console.log(item);

return (
<div>
<h2>Please proceed to give me your card details!</h2>
<p>
{item[0].id}
{item[0].name}
{item[0].price}
{item[0].image}
</p>
{searchParams.id}
</div>
);
}
to start with
b1mind
b1mindā€¢8mo ago
that work?
CDL
CDLā€¢8mo ago
useSearchParams isnt a function, so it's not accepting useSearchParams()
b1mind
b1mindā€¢8mo ago
or it blow up? oh mate... yea I feel like I'm just giving you code and you still are missing the understanding
CDL
CDLā€¢8mo ago
I'm kinda reading off the bugs im getting
b1mind
b1mindā€¢8mo ago
you should know why this is happening think about it for a second like this is a core JS thing not even to do with React
export default function Cart({ searchParams }) {
const searchParams = useSearchParams();
export default function Cart({ searchParams }) {
const searchParams = useSearchParams();
keep in mind also the error you get. Two things wrong Don't get frustrated either.. I'm not trying to make you feel dumb we need to make sure you understand what the code is doing here. this is important
CDL
CDLā€¢8mo ago
you're good, I need to understand lol
b1mind
b1mindā€¢8mo ago
I feel like we should just get in voice chat it too late there probably though huh? I don't want to bug your misses
CDL
CDLā€¢8mo ago
nah i'm good for an hour or so
b1mind
b1mindā€¢8mo ago
lets goto priv chat const id = searchParams.id;
CDL
CDLā€¢8mo ago
No description
CDL
CDLā€¢8mo ago
import React from "react";
import posts from "../data";

export default function Cart({ searchParams }) {
console.log(searchParams.id); // Logs post.id value from url
const id = searchParams.id;
const item = posts.filter((post) => post.id !== id);
console.log(item);

return (
<div>
<h2>Please proceed to give me your card details!</h2>
<p>
{item[0].id}
{item[0].name}
{item[0].price}
{item[0].image}
</p>
{searchParams.id}
</div>
);
}
import React from "react";
import posts from "../data";

export default function Cart({ searchParams }) {
console.log(searchParams.id); // Logs post.id value from url
const id = searchParams.id;
const item = posts.filter((post) => post.id !== id);
console.log(item);

return (
<div>
<h2>Please proceed to give me your card details!</h2>
<p>
{item[0].id}
{item[0].name}
{item[0].price}
{item[0].image}
</p>
{searchParams.id}
</div>
);
}
b1mind
b1mindā€¢8mo ago
now put this in cart.jsx
CDL
CDLā€¢8mo ago
No description
b1mind
b1mindā€¢8mo ago
this is like a small bit
No description
b1mind
b1mindā€¢8mo ago
const [todos, setTodos] = useState([]);
const [todoItem, setTodoItem] = useState('');
const [todos, setTodos] = useState([]);
const [todoItem, setTodoItem] = useState('');
useEffect(() => {
const filteredItems = items.filter(item => item.id === id);
setItems(filteredItems);
}, [id, items]);
useEffect(() => {
const filteredItems = items.filter(item => item.id === id);
setItems(filteredItems);
}, [id, items]);
This is all your missing I think replace the old useEffect filter with this one
CDL
CDLā€¢8mo ago
I think we had that before, no? getting the same 3 errors as earlier, hydration etc.
b1mind
b1mindā€¢8mo ago
kk well let someone Reacty hlep in the other post get some zzz's
Want results from more Discord servers?
Add your server