I'm making a shopping cart component with Next.js and having an issue refreshing cart data after updating it. My cart component is a function as recommended on Next.js documentation (https://nextjs.org/docs/basic-features/data-fetching#fetching-data-on-the-client-side) and I have a component inside this called products.js, containing my list of products, which each have +/- buttons to adjust their qty (post to the database).
My database updates, but I need to re-fetch the data clientside on the cart component. I've realized I can re-fetch the swr call using swrs 'mutate', but when I try to pass a callback function from my cart.js to products.js it shows up in console log, but isn't called on my button click.
I have tried cartUpdate = cartUpdate.bind(this)
and also looked into hooks the last couple days and tried other things but could use some advice.
If cart.js were a class component I would bind my cartUpdate
function before passing it down to product.js and this would work, but I can't seem to do the same when it's function to function vs class to function.
I've been on this a couple of days and I'm not sure If I'm trying to go against some rules I don't know about or how I can re-fetch my data while still keeping my code separated and somewhat clean.
products.js:
export default function productsection ({products, cart, cartproducts, feUpdate}){
console.log("feUpdate", feUpdate)
return (
<div>
{products.map((product, i) => (
<div className="flex-column justify-content-center mx-2">
<div className="mx-auto card w-100 p-2 my-2">
<div className="card-body ">
<h5 className="card-title text-center">{product.name}</h5>
<div className="d-flex justify-content-between">
{/* <p>Size Selected: {product.size}</p> */}
{/* <p>Total: {product.price * props.cartproducts[i].qty} USD</p> */}
<button className='btn btn-light mx-2' onClick={() => {
fetch(`/api/db/editCartProducts`,{
method: 'post',
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({task: 'ADD', orderid: cart.orderid, productid: product.productid})
}).then(res => {console.log("adding: " + product.name + " from cart.", "id: " + product.productid); () => feUpdate(); console.log("passed update")})
}}
>
Add
</button>
<p className="px-2">Price: {product.price} USD EA</p>
<p className="px-2">{product.description}</p>
<p>Quantity: {cartproducts[i].qty}</p>
<button className='btn btn-light mx-2' onClick={() => {
fetch(`/api/db/editCartProducts`,{
method: 'post',
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({task: 'REMOVE', orderid: cart.orderid, productid: product.productid})
}).then(res => {console.log("removing: " + product.name + " from cart.", "id: " + product.productid);() => feUpdate(); console.log("passed update")})
}}>
Remove
</button>
</div>
</div>
</div>
</div>
))}
</div>
)
}
cart.js: (main points are cartUpdate()
& ProductSection
which I'm passing cartUpdate
into)
function Cart (props){
const fetcher = (...args) => fetch(args[0], {
method: 'post',
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({[args[2]]:args[1]})
}).then(res => res.json())
let User = Cookies.get('User')
async function cartUpdate(){
console.log("mutate called");
console.log("isValidated: ", isValidating)
mutate();
console.log(cartitems);
console.log("isValidated: ", isValidating)
}
const { data: user, error} = useSWR(() => [url1, User, "User"], fetcher, {suspense: false });
console.log("User returned: ", user)
const { data: cart, error2} = useSWR(() => [url2, user.customerid, 'User'], fetcher, { suspense: false });
console.log("Cart returned: ", cart)
// const OrderId = Cookies.get('orderid')
const { data: cartitems, error3, mutate, isValidating} = useSWR(() => [url3, cart.orderid, 'orderid'], fetcher, { suspense: false });
console.log("Cart items: ", cartitems)
console.log("before productdetails call")
const { data: productdetails, error4} = useSWR(() => [url4, cartitems, 'productids'], fetcher, { suspense: false });
console.log("productdetails: ", productdetails)
let itemtotal = 0;
let costtotal = 0;
if(productdetails && cartitems){
productdetails.forEach((product, i) => {
itemtotal = itemtotal + (cartitems[i].qty);
costtotal = costtotal + (product.price * cartitems[i].qty)
})
console.log("totals: ", itemtotal, costtotal)
}
if (productdetails) {
console.log(props)
// foreach to get total price of cart and total items count.
return (
<div className="jumbotron jumbotron-fluid mt-5 d-flex flex-column justify-content-center">
<Header name={user.fname}/>
<div className={!isValidating? "card text-center" : "text-center"}>isValidating??</div>
<div className="d-flex flex-row justify-content-center">
<button onClick={() => feUpdate()}>Big Update Button</button>
<ProductSection feUpdate={cartUpdate} products={productdetails} cart={cart} cartproducts={cartitems} />
<Summery itemtotal={itemtotal} costtotal={costtotal}/>
</div>
</div>
)
}
Are you using the global mutate
(yes there're 2 of them)? Then you need to pass a SWR key to it.
Global mutate
:
import useSWR, { mutate } from 'swr'
...
const { data } = useSWR(key, fetcher)
mutate(key) // this will trigger a refetch
Or using bound mutate
, and you don't need to pass the key
:
import useSWR from 'swr'
...
const { data, mutate } = useSWR(key, fetcher)
mutate() // this will trigger a refetch
So just to close this off, I came back to it after working on other areas of the project and realized it was as simple as using a normal function call instead of arrow function e.g. .then(res => {feUpdate()})
don't know how I overlooked this or what was going on with testing before but it's working now. I guess taking a break and coming back with fresh eyes does the trick.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With