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.
B
b1mind43d 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)
C
CDL42d 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.
B
b1mind42d 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
C
CDL42d ago
It's the last front-end project from TOP so using BE is cheating there, so I can't use it
B
b1mind42d ago
Local storage is nice but yea you can't see it on a server.
C
CDL42d ago
has to be FE only
B
b1mind42d ago
Huh 😂
C
CDL42d ago
am I wrong? 😄
B
b1mind42d 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
B
b1mind42d 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...
B
b1mind42d 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)
C
CDL42d ago
sorry was watching a last of the mohicans clip lol
B
b1mind42d ago
I would think you can access the formAPI with a RSC but I don't see it off a quick search.
C
CDL42d ago
so the plan is literally just build a shopping cart like i have done without the cart part
B
b1mind42d ago
fail
C
CDL42d ago
Project: Shopping Cart | The Odin Project
The Odin Project empowers aspiring web developers to learn together for free
B
b1mind42d ago
At the very least you should do a simple localStorage state
C
CDL42d ago
sorry I meant it requires the cart, but i haven't done that yet
B
b1mind42d ago
oh don't turn it in I'll fail ya <,<;; 🤣
C
CDL42d 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
B
b1mind42d 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
C
CDL42d ago
oh, hmm
B
b1mind42d ago
and use searchParam method on the that page to get the id
C
CDL42d ago
yeah nextjs is the "issue", havent a clue on the fucking thing forthe most part, nothing seems teh same as react
B
b1mind42d ago
then you can get just that id from yoru dataset that is because just React sux bawls
C
CDL42d ago
even litle things like = useState() is actually = React.useState() -.-
B
b1mind42d 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
C
CDL42d ago
TOP admins shouted at me for using next 😦 bullies i think they use CRA still, which I thought was bsically redundant now
B
b1mind42d 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) 😂
C
CDL42d 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 🧙‍♂️ 🤣
B
b1mind42d ago
I mean yes then you just have to store it.
C
CDL42d ago
This guy seems like he knows what he's doing https://www.youtube.com/watch?v=LcaqzH6-XkY
B
b1mind42d 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
C
CDL42d 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
B
b1mind42d ago
mate... I'm telling you its how the web works EVERYONE DOES IT BUT REACT BRAIN PEOPLE
C
CDL42d ago
🤣
B
b1mind42d ago
cause they have fucking react brain NextJS is a MPA framework now I gave you the answer in the SO poast
C
CDL42d ago
so you're saying all i need is searchParam to do this
B
b1mind42d 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
C
CDL42d ago
ah
B
b1mind42d 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
C
CDL42d ago
This iswhat you're on about yeah
No description
B
b1mind42d ago
you do that with dynmaic routes [id] or ?id=313421 in the URL
C
CDL42d ago
I get what you're on about
B
b1mind42d 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 😂
C
CDL42d 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 😛
B
b1mind42d 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 🤣
C
CDL42d ago
sorry was grabbing my dinner, let me catch up reading
B
b1mind42d ago
np I should eat too lunch time here.
C
CDL42d ago
are those 2 snippets the same "set"? or is that 2 different variations of how to do this oh, they work together
B
b1mind42d ago
those are your two pages
C
CDL42d ago
that's all I need...?
B
b1mind42d 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
C
CDL42d ago
ah ok so this you can maybe explain
C
CDL42d ago
No description
C
CDL42d ago
It's literally just 'use client' at the top?
B
b1mind42d ago
yes that string has to be first at the top of your file faik or you can do the back end one
C
CDL42d ago
should it be post.filter?
B
b1mind42d ago
no you need to filter from your array
C
CDL42d ago
No description
B
b1mind42d ago
did you import it?
C
CDL42d ago
fucking imports man.. yeah i have now
B
b1mind42d ago
gotta have em lol
C
CDL42d 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
B
b1mind42d ago
necessary evil ig 😂 did you import Link? also it will be a link not a button
C
CDL42d ago
that'll be because of Link yeah
B
b1mind42d ago
you can just add your styles to it
C
CDL42d ago
that's fine I need to test why it's just white screening me then
B
b1mind42d 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>
);
C
CDL42d ago
it does change to http://localhost:3000/cart?id=2 when you click
B
b1mind42d ago
yea yea that part works I know its the cart component we need to fix
C
CDL42d ago
ah I mean, there's nothing in here atm right
B
b1mind42d ago
You are teaching me next 🤣
C
CDL42d ago
just logic
B
b1mind42d 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
C
CDL42d ago
same result
B
b1mind42d ago
did your cart page ever work? like render the h2
C
CDL42d ago
yeah it would show the html wait am i keeping any of the previous code?
B
b1mind42d ago
no
C
CDL42d 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;
B
b1mind42d ago
you have to export ya dork
C
CDL42d ago
it's exporting "export default function"
B
b1mind42d ago
that is not the 'use client' oh wait ya comment out 'use client' sorry I had them mixed up xD
C
CDL42d ago
np i need to keep the searchParams const in there though don't I
B
b1mind42d 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
C
CDL42d 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
B
b1mind42d 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
C
CDL42d 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
B
b1mind42d 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})
C
CDL42d ago
WAIT WE HAVE SOMETHING
B
b1mind42d ago
muhahah getting there!
C
CDL42d ago
No description
B
b1mind42d ago
winning!!!
C
CDL42d ago
oh shit
B
b1mind42d 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
C
CDL42d ago
so we added Link to shop and added searchParams to cart
B
b1mind42d 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.
C
CDL42d ago
and when you click on the link, its posting that id to the cart
B
b1mind42d ago
yup
C
CDL42d ago
ok I like that
B
b1mind42d ago
Like right now put any number in your URL
C
CDL42d ago
that's wayyyyy less code than context
B
b1mind42d ago
42069 and it should render that number on the page
C
CDL42d ago
yeah it renders
B
b1mind42d ago
So that is the most basic and core way to pass info on the web
C
CDL42d 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
B
b1mind42d 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?
C
CDL42d ago
if you go to shop and come back to cart, it does vanish though
B
b1mind42d ago
yes and do you know why?
C
CDL42d ago
well i dont think im saving it anywhere am i?
B
b1mind42d ago
correct! but real fast before you do that we need more than the id right?
C
CDL42d ago
yep i need the lot
B
b1mind42d 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
C
CDL42d ago
where'd your posts.filter come from
B
b1mind42d 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
C
CDL42d ago
it's not finding item atm, need to solve that bit then i can look at the array
B
b1mind42d ago
console.log(item) before the return if its an array of one 😂
C
CDL42d ago
No description
B
b1mind42d 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);
C
CDL42d ago
I was following until you mentioned filter and then I got a littel confused
B
b1mind42d 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
C
CDL42d 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
B
b1mind42d ago
that work?
C
CDL42d ago
useSearchParams isnt a function, so it's not accepting useSearchParams()
B
b1mind42d ago
or it blow up? oh mate... yea I feel like I'm just giving you code and you still are missing the understanding
C
CDL42d ago
I'm kinda reading off the bugs im getting
B
b1mind42d 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
C
CDL42d ago
you're good, I need to understand lol
B
b1mind42d 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
C
CDL42d ago
nah i'm good for an hour or so
B
b1mind42d ago
lets goto priv chat const id = searchParams.id;
C
CDL42d ago
No description
C
CDL42d 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>
);
}
B
b1mind42d ago
now put this in cart.jsx
C
CDL42d ago
No description
B
b1mind42d ago
this is like a small bit
No description
B
b1mind42d 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
C
CDL42d ago
I think we had that before, no? getting the same 3 errors as earlier, hydration etc.
B
b1mind42d ago
kk well let someone Reacty hlep in the other post get some zzz's
Want results from more Discord servers?
Add your server
More Posts
Responsive Design Q#1I listed this as Q#1 because I anticipate having more similar questions. Normally, when I just plaOverlay gradient not workingTrying to understand why this isn't working.. i want the gradient to go below the parent DIV and bleKeybinds for Nav BarWhat is the simplest way to have a keybind open a link? ( I have a navbar with 4 robust pages linkednext.js and vercelhow to fix thatFlickering/glitching issue while applying the CSS animation.Hello everyone, I designed a "slide to unlock" component in React. It doesn't work as expected. Somusing styled components override the styles of other componentI had dialog `export const Dialog : React.FunctionComponent<Props> = (props) => { return ( Need my column to take up the full height of the available space on desktop - probably simple!Hey there. Probably missing something silly here, but my head is jelly for the time being. - I haBest way to make this Frontend Mentor challenge accessible?I was looking at this UI challenge by Frontend Mentor and I was wondering what would be the most accposition:fixed; scroll-yI have a mobile header with `position: fixed;` style. It has a lot of menu items that make the last Responsive Carousel V2Goal: Create a responsive carousel for all screensizes Here is my attempted solution - https://codeHow to use Git in command lineI can't understand this. I litterally just want to upload some files, but they make it impossible.Installing a library with JSHello, I'm trying to build a demo bar code scanner. I found this library: https://serratus.github.ioNested route problemI have a nested route system, One is in App.js and one in RoomGuard component The app.js has router Max width with fr in grid.Hi, I am trying to limit breakout in the grid to a amx width but would like to retain ints atributesopen full stackNot sure how useful this will be but it looks useful for understanding fullstack. Trigger warning: rchange default keyboard layout without changing the default language in windows 11windows 11 has plenty of flaws, and one of them is how badly it accommodates people who speak multipHaving problem in wrapping custom hooks with React componentThis is my code:- const App = () => { return ( <Router> <Routes> <RoFind new positions of elementsPlease watch the following video, in question 5 when I connect the answers together they are followiPosition Sticky stops working, after I set a sibling element to Position Absolute```html <header> <div class="logo"></div> <div class="header__links"></div> <nav class="nav"><question regarding "key" in jsIk this might seem a lil dumb but can someone explain to me why we use "key" in js or react as well