By continuing you indicate that you have read and agree to our Terms of service and Privacy policy
by DissentDifference Python Version: Current License: No License
by DissentDifference Python Version: Current License: No License
Download this library from
Support
Quality
Security
License
Reuse
kandi has reviewed DarkWallet and discovered the below as its top functions. This is intended to give you an instant insight into DarkWallet implemented functionality, and help decide if they suit your requirements.
Bitcoin privacy wallet for anonymous anarchist hackers
DarkWallet - Bitcoin privacy wallet for anonymous anarchist hackers
$ wget -q -O- https://raw.githubusercontent.com/RojavaCrypto/launderwallet/master/scripts/install.sh | bash
QUESTION
React state object turning into "[object Object]" on refresh using sessionStorage
Asked 2022-Mar-23 at 14:53I'm working on a dummy fullstack ecommerce app using Postgres, Express and React whilst going through a fullstack course. This question is pretty specific to React.
On login to the app I can successfully create or retrieve a cart from the db and save it to state. It's being saved as a normal object:
Cart: {id: 2, user_id: 159, product_count: 0, price: '£0.00'}
-From Chrome Dev Tools: Extensions React Developer Tools.
I'm then using React useEffect hooks to persist this state in sessionStorage:
App.js
useEffect(() => {
if (sessionStorage["cart"]) {
setCart(window.sessionStorage.getItem("cart"));
}
}, []);
useEffect(() => {
window.sessionStorage.setItem("cart", cart);
}, [cart]);
Whenever I refresh the page or go to another route the normal object seems to be turning into the string: "[object Object]".
I know it has something to do with the way I'm saving the cart state variable into the localStorage but I'm not familiar with it enough to know exactly where this is happening or how to fix it so any help would be appreciated.
I've tried changing the assignment variables within the useEffect calls to include trying to save the item as an object, but I'm not familiar enough with sessionStorage to know what's happening behind the scenes.
ANSWER
Answered 2022-Mar-23 at 14:53When you store the object to storage, call JSON.stringify(cart) to convert from an object to a string.
When you read the object from storage, it's const cart = JSON.parse(cartString)
to convert from the string back into an object.
Like so:
useEffect(() => {
if (sessionStorage["cart"]) {
setCart(JSON.parse(window.sessionStorage.getItem("cart")));
}
}, []);
useEffect(() => {
window.sessionStorage.setItem("cart", JSON.stringify(cart));
}, [cart]);
QUESTION
Render all products that relate to one of subcategories of one category, in category page
Asked 2022-Mar-07 at 16:38I had a question. I am creating an ecommerce website in django. There, I have categories and subcategories. When I enter to subcategory page, I able to render all products that relate to this subcategory. But, when I wanted to render all product that relate on one parent category, I am having troubles. So, I have some subcategories in one category. In that category page, I want to render all products that relate to one of subcategories of this category. Can you help me please? models.py
class Category(models.Model):
parent = models.ForeignKey('self', related_name='children', on_delete=models.CASCADE, blank=True, null=True)
title = models.CharField(max_length=255)
slug = models.SlugField(max_length=255)
image = models.ImageField(null=True, blank=True, verbose_name="Изображение")
ordering = models.IntegerField(default=0)
is_featured = models.BooleanField(default=False)
class Meta:
verbose_name_plural = 'Categories'
ordering = ('ordering',)
def __str__(self):
if self.parent is not None:
return f"{self.parent}/{self.title}"
return self.title
@property
def imageURL(self):
try:
url = self.image.url
except:
url = ''
return url
def get_absolute_url(self):
return '/%s/' % (self.slug)
class Product(models.Model):
category = models.ForeignKey(Category, related_name='products', on_delete=models.CASCADE)
parent = models.ForeignKey('self', related_name='variants', on_delete=models.CASCADE, blank=True, null=True)
name = models.CharField(max_length=200, verbose_name="Название продукта")
price = models.IntegerField(verbose_name="Цена")
slug = models.SlugField(max_length=255)
description = models.CharField(max_length=5000,blank=True, verbose_name="Описание:")
image = models.ImageField(null=True, blank=True, verbose_name="Изображение")
novinki = models.BooleanField(default=False, verbose_name="Новинки")
popularnye = models.BooleanField(default=False, verbose_name="Популарные")
def __str__(self):
return self.name
class Meta:
verbose_name = 'Продукты'
verbose_name_plural = "Продукты"
@property
def imageURL(self):
try:
url = self.image.url
except:
url = ''
return url
views.py
def category_detail(request, slug):
data = cartData(request)
cartItems = data['cartItems']
order = data['order']
items = data['items']
categories_for_menu = Category.objects.filter(parent=None)[:3]
categories = Category.objects.filter(parent=None)
category = get_object_or_404(Category, slug=slug)
**products_all = Product.objects.filter(category.parent==category)**
print(products_all)
products = category.products.all()
context = {'items' : items, 'order' : order, 'cartItems' : cartItems, 'products':products, 'category':category, 'categories':categories,'categories_for_menu':categories_for_menu,'products_all':products_all}
return render(request, "store/categories.html", context)
Here I want to save all products that relate the category in products_all. Looking forward to your help!
ANSWER
Answered 2022-Mar-07 at 14:48You can do it using Q function:
from django.db.models import Q
category = get_object_or_404(Category, slug=slug)
products = Product.objects.filter(Q(category = category)|Q(category__parent = category))
QUESTION
UseParams() not working and not rendering data on screen
Asked 2022-Feb-17 at 08:58I am working on an eCommerce website and I am stuck . I am mapping through a array and it renders Image and a link . I want to click the link(checkitem) on image and it should open the Image and detail in different page but its not working. I am using reactrouter for it and passing the id of the image to useparams() in my Fullcard component . In my Full card component i am filtering and mapping the array according to the id of the image , but it seems to not work .Can you guys help me.
Here is the CodeSandboxLink of the project : https://codesandbox.io/s/strange-driscoll-gpl629?file=/src/App.js
Here is my Appjs :
import Hero from './Hero';
import { BrowserRouter as Router, Route, Routes } from "react-router-dom";
import FullCard from "./FullCard";
function App() {
const data = [
{
burh: "1fdsd",
id: 1,
img: "https://d3o2e4jr3mxnm3.cloudfront.net/Mens-Jake-Guitar-Vintage-Crusher-Tee_68382_1_lg.png",
},
{
burh: "1fdsd",
id: 2,
img: "https://cdn.shopify.com/s/files/1/0101/4832/products/Angela_Natural_Tee.png?v=1606780388",
},
{
burh: "1fdsd",
id: 3,
img: "https://www.prada.com/content/dam/pradanux_products/U/UCS/UCS319/1YOTF010O/UCS319_1YOT_F010O_S_182_SLF.png",
},
{
burh: "1fdsd",
id: 4,
img: "https://www.burdastyle.com/pub/media/catalog/product/cache/7bd3727382ce0a860b68816435d76e26/107/BUS-PAT-BURTE-1320516/1170x1470_BS_2016_05_132_front.png",
},
];
return (
<Router>
<Routes>
<Route path="/" element={<Hero data={data}/>} />
<Route path="/products/:id" element={ <FullCard data={data} />} />
</Routes>
</Router>
);
}
export default App;
Here is my Card:
// import { popularProducts } from "./data";
import { Link } from "react-router-dom";
import "./Card.css";
const Card = ({ data }) => {
return (
<div className="Maincontainer">
<div className="CardContainer">
{data.map((items, index) => {
return (
<div className="cards" key={index}>
<img src={items.img} alt="/" />
<Link to={`/products/${items.id}`}>CheckItem</Link>
</div>
);
})}
</div>
</div>
);
};
export default Card;
Here is my Full card comp:
import { useParams } from 'react-router-dom'
const FullCard = ({data}) => {
const {id} = useParams();
return (
<div className='container'>
{data.filter( (items )=> items.id === id ).map((items,index) =>{
return (
<div key={items} className="container2">
<h1>{items.burh}</h1>
{/* <img src={items.image} alt="/" /> */}
</div>
);
})}
</div>
)
}
ANSWER
Answered 2022-Feb-17 at 06:32The id
properties in data
are number types, but the id
route match param will be a string. The data filtering in FullCard
is failing because you are using strict equality, which requires both operands to be of the same type. In this case, either both numbers or both strings.
{data
.filter((items) => items.id === id) // <-- type mismatch comparision
.map((items, index) => {
return (
<div key={items.id} className="container2">
<h1>{items.burh}</h1>
{/* <img src={items.image} alt="/" /> */}
</div>
);
})}
Either use loose equality, i.e. ==
so type coercion/conversion is attempted in determining equality
.filter((items) => items.id == id)
or convert the items.id
to a string and use string equality
.filter((items) => String(items.id) === id)
QUESTION
Problem with create table Category and get the url correctly PHP
Asked 2022-Feb-03 at 07:22I am creating an ecommerce, which can have Men's Fashion, Women's Fashion or Children's Fashion, it could also have more in the fure like Sports, Electronics, etc.
But I don't know if I have, for example, to repeat the categories clothes, etc for each one or not, I don't know if there is a better way. Since I must also create the dynamic menu
My table structure is like this:
CREATE TABLE `category`(
`category_id` smallint(3) unsigned not null auto_increment primary key,
`category_name` VARCHAR(40) NOT NULL,
`category_url` VARCHAR(40) NOT NULL,
`icon`varchar(150) default null,
`gender` enum('Men','Woman','Baby') default null,
`parent` INT DEFAULT NULL
)engine=InnoDB default charset=utf8mb4 collate=utf8mb4_spanish_ci;
Some posible inserts what i want:
INSERT INTO `category` (`category_id`, `category_name`, `category_url`, `icon`, `gender`, `parent`) VALUES
-- Mens section
(1, 'Mens Fashion', 'mens-fashion', null, null, null), -- Mens fasion
-- clothes mens
(2, 'Clothing', 'clothing', 'clothing.svg', null, 1), -- (level 2)
(3, 'Shoes', 'Shoes', 'shoes.svg', null, 1), -- (level 2)
(4, 'Complements', 'complements', 'complements.svg', null, 1), -- (level 2)
(5, 'Shirts', 'shirts', null, null, 2), -- (level 3)
(6, 'Casual shirts', 'casaul-shirts', null, null, 5), -- (level 4)
(7, 'Suit shirts ', 'suit-shirts', null, null, 5), --(level 4)
(8, 'Jeans', 'jeans', null, null, 2), -- (level 3)
(9, 'Jeans skinny', 'jeans-skinny', null, null, 8), -- (level 4)
(10, 'Jeans slim fit', 'jeans-slim-fit', null, null, 8), -- (level 4)
(11, 'Underwear', 'Underwear', null, null, 2), -- (level 3)
(12, 'Socks', 'socks', null, null, 11), -- (level 4)
-- Woman section
(13, 'Woman Fashion', 'woman-fasion', null, null, null), -- (level 1)
-- Clothes woman
(14, 'Clothing', 'clothing', 'clothing.svg', null, 13), -- (level 2)
(15, 'Shoes', 'Shoes', 'shoes.svg', null, 13), -- (level 2)
(16, 'Complements', 'complements', 'complements.svg', null, 13), -- (level 2)
(17, 'Shirts', 'shirts', null, null, 13), -- (level 3)
(18, 'Casual shirts', 'casaul-shirts', null, null, 17), -- (level 4)
(19, 'Suit shirts', 'suit-shirts', null, null, 17), -- (level 4)
(20, 'Top shirt', 'top-shirt', null, null, 17), -- (level 4)
(21, 'Jeans', 'jeans', null, null, 13), -- (level 3)
(22, 'Jeans skinny', 'jeans-skinny', null, null, 21), -- (level 4)
(23, 'Jeans slim fit', 'jeans-slim-fit', null, null, 21), -- (level 4)
(24, 'Underwear', 'Underwear', null, null, 13), -- (level 3)
(25, 'Socks', 'socks', null, null, 24), -- (level 4)
-- Childeren section
(13, 'Childerens Fasion', 'childeren-fashion', null, null, null), -- (level 1)
-- Clothes childeren etc..
It's that ok what I'm doing, repeat for each section the same categories as clothes, Jeans, etc.?
I really do this because otherwise I don't know how to create the menu gives the image that I leave below
Another question i have.
I am creating this menu, with said table, which is what I want to obtain.
Is there any way to get the url in this way:
mens-fashion/clothing/shirts
because for example shirts would be the url above.
So what i mean, if the category is level 4, the url would be: level1/level2/level3/level4.
What would be better:
To add it directly to my table the absolute path or
can i do that with PHP, i leave the code that I am using.
$categories = $db->query('SELECT category_id, category_url, parent, category_name FROM category ORDER BY category_id');
$cat = $categories->fetchAll(PDO::FETCH_ASSOC);
$arrayMenu = array();
foreach($cat as $row){
$arrayMenu[$row['category_id']] = array("parent" => $row['parent'], "category_name" => $row['category_name'], "category_url" => $row['category_url']);
}
function createTree($array, $curParent, $currLevel = 0, $prevLevel = -1) {
foreach ($array as $categoryId => $category) :
if ($curParent == $category['parent']) :
if($category['parent']==0) $class="dropdown"; else $class="sub_menu";
if ($currLevel > $prevLevel) echo " <ul class='$class'> ";
if ($currLevel == $prevLevel) echo " </li> ";
echo '<li id="'.$categoryId.'" ><a href="'.$category['category_url'].'">'.$category['category_name'].'</a>';
if ($currLevel > $prevLevel) { $prevLevel = $currLevel; }
$currLevel++;
createTree ($array, $categoryId, $currLevel, $prevLevel);
$currLevel--;
endif;
endforeach;
if ($currLevel == $prevLevel) echo " </li> </ul> ";
}
?>
<div class="nav">
<?php
if ($cat != null) createTree($arrayMenu, 0);
?>
I tried to add this line to get, for example, the level 1 url, but it doesn't:
$url_level1 = ($row['parent'] == 0) ? $row['category_url'] : '';
Edit:
The css with which I was testing: (It doesn't really have styles and it's outdated)
nav ul li {
background:#f1f1f1; list-style: none;
}
ul.dropdown {
position:relative;
width:auto;
font:12px Arial, Helvetica, sans-serif;
}
ul.dropdown li {
float:left; zoom:1;
height:auto;
min-height: 30px;
padding:6px 2px 0 2px;
}
ul.dropdown li li {
border-right:1px solid #ccc;
border-left:1px solid #ccc;
margin-left:-30px;
}
ul.dropdown a:hover {
color:#000;
}
ul.dropdown a:active { color:#ffa500; }
ul.dropdown li a {
display:block;
padding:4px 8px;
color:#000;
text-decoration:none;
font:bold 12px Arial, Helvetica, sans-serif;
}
ul.dropdown li:last-child a { border-right:none;} /* Doesn't work in IE */
ul.dropdown li:hover {
color:#000;
background:#e7e7e7;
position:relative; }
ul.dropdown li.hover a { color:#000; }
ul.dropdown ul {
text-align:left;
visibility: hidden;
position: absolute;
left:-10px;
top:36px; }
ul.dropdown ul li {
background:#f1f1f1;
border-bottom:1px solid #ccc;
float:none; width:120px;
height:auto;
min-height: 25px;
}
ul.dropdown ul li a {
border-right:none;
width:100%;
display:inline-block; color:#000; }
ul.dropdown ul ul {
left:100%;
top:0;
}
ul.dropdown li:hover > ul { visibility:visible; }
Note: What I realy was creating was something like this:
// Tab header ///////
function openPage(pageName, elmnt, color) {
// Hide all elements with class="tabcontent" by default */
var i, tabcontent, tablinks;
tabcontent = document.getElementsByClassName("tabcontent");
for (i = 0; i < tabcontent.length; i++) {
tabcontent[i].style.display = "none";
}
// Remove the background color of all tablinks/buttons
tablinks = document.getElementsByClassName("tablink");
for (i = 0; i < tablinks.length; i++) {
tablinks[i].style.background = "";
}
// Show the specific tab content
document.getElementById(pageName).style.display = "block";
// Add the specific color to the button used to open the tab content
elmnt.style.background = color;
}
// Get the element with id="defaultOpen" and click on it
document.getElementById("defaultOpen").click();
// Accordion ///////
var acc = document.getElementsByClassName("accordion");
var i;
for (i = 0; i < acc.length; i++) {
acc[i].addEventListener("click", function() {
this.classList.toggle("active");
var panel = this.nextElementSibling;
if (panel.style.maxHeight) {
panel.style.maxHeight = null;
} else {
panel.style.maxHeight = panel.scrollHeight + "px";
}
});
}
/* TAB HEADER MENU */
#wrapper-tablink {
display: flex;
flex-flow: row nowrap;
justify-content: center;
align-items: center;
}
/* Style tab links */
.tablink {
background-color: #555;
color: white;
border: none;
outline: none;
cursor: pointer;
padding: 14px 16px;
font-size: 17px;
width: 25%;
}
.tablink:hover {
background-color: #777;
}
.tablink .active {
color: #000;
}
/* Style the tab content (and add height:100% for full page content) */
.tabcontent {
color: white;
display: none;
padding: 100px 20px;
height: 100%;
overflow-y: auto;
}
/*
#moda-mujer {background-color: var(--secundary-color);}
#moda-hombre {background-color: #00cc99;}
#electronica {background-color: #3399ff;}
#cursos {background-color: #9933ff;}
*/
.wrapper-icons-bars {
display: flex;
flex-flow: row nowrap;
justify-content: center;
align-items: center;
margin: 10px 0 20px 0;
}
.wrapper-icons-bars a {
display: block;
position: relative;
background-color: #FFFFFF;
border-bottom: 3px solid var(--body-color);
border-right: 1px solid #F1F1F1;
padding: 20px;
transition: all 0.3s ease;
}
.wrapper-icons-bars a:hover {
display: block;
position: relative;
border-bottom: 3px solid var(--secundary-color);
padding: 25px;
transition: all 0.3s ease;
}
/* ACCORDIAN CONTENT */
.wrapper-accordion {
display: flex;
justify-content: center;
width: 100%;
margin-bottom: 80px;
}
.accordion {
display: flex;
position: relative;
justify-content: center;
align-items: center;
background-color: #eee;
color: #444;
cursor: pointer;
padding: 18px;
width: 100%;
max-width: 500px;
min-width: 500px;
border: none;
text-align: left;
outline: none;
font-size: 15px;
transition: 0.4s;
}
.active,
.accordion:hover {
background-color: #ccc;
}
.accordion:after {
content: '\002B';
color: #777;
font-weight: bold;
display: block;
position: absolute;
right: 25px;
margin-left: 5px;
}
.active:after {
content: "\2212";
}
.panel {
background-color: white;
color: var(--body-color);
max-height: 0;
width: 100%;
overflow: hidden;
transition: max-height 0.2s ease-out;
}
.inner-panel {
padding: 20px 20px;
width: 100%;
max-width: 500px;
}
.wrapper-accordion a {
color: var(--body-color);
}
<!-- Create Tab links header (Table: controllers) -->
<div id="wrapper-tablink">
<button class="tablink" onclick="openPage('mens-fashion', this, 'blue')" id="defaultOpen">Mens Fashion</button>
<button class="tablink" onclick="openPage('womans-fashion', this, 'red')" id="defaultOpen">Womans Fashion</button>
</div>
<div id='mens-fashion' class='tabcontent' style='blue'>
<article class='wrapper-accordion'>
<div>
<h2><a href='mens-fashion/clothes'>Clothes</a></h2>
<div class='wrapper-icons-bars'>icons</div>
<button class='accordion active'>Clothes</button>
<div class='panel' style='max-height: 1000px;'>
<div class='inner-panel'>
<h5><a href='mens-fashion/clothes'>Clothes</a></h5>
<a>Tshirt </a>
</div>
</div>
<button class='accordion'>Shoes</button>
<div class='panel'>
<div class='inner-panel'>
<h5><a href='mens-fashion/shoes'>Shoes</a></h5>
<a>Deport shoes </a>
</div>
</div>
<button class='accordion'>Complements</button>
<div class='panel'>
<div class='inner-panel'>
<h5><a href='mens-fashion/complemnts'>Shoes</a></h5>
<a>Clock </a>
</div>
</div>
</div>
</article>
</div>
<div id='womans-fashion' class='tabcontent' style='red'>
<article class='wrapper-accordion'>
<div>
<h2><a href='womans-fashion/clothes'>Clothes</a></h2>
<div class='wrapper-icons-bars'>icons</div>
<button class='accordion active'>Clothes</button>
<div class='panel' style='max-height: 1000px;'>
<div class='inner-panel'>
<h5><a href='womans-fashion/clothes'>Clothes</a></h5>
<a>Tshirt </a>
</div>
</div>
<button class='accordion'>Shoes</button>
<div class='panel'>
<div class='inner-panel'>
<h5><a href='womans-fashion/shoes'>Shoes</a></h5>
<a>Deport shoes </a>
</div>
</div>
<button class='accordion'>Complements</button>
<div class='panel'>
<div class='inner-panel'>
<h5><a href='womans-fashion/complemnts'>Shoes</a></h5>
<a>Clock </a>
</div>
</div>
</div>
</article>
</div>
ANSWER
Answered 2022-Feb-03 at 07:22It's that ok what I'm doing, repeat for each section the same categories as clothes, Jeans, etc.?
Yes, It's perfectly okay to do that. Personally, that is what I prefer.
What would be better: To add it directly to my table the absolute path or can i do that with PHP
You can easily achieve it with PHP.
Kindly use these functions to generate the markup for the nested categories. You can modify the HTML to achieve your desired results.
// convert the categories array to parents with nested children
function convertToLevels ($array) {
// First, convert the array so that the keys match the ids
$reKeyed = array();
foreach ($array as $item) {
$reKeyed[$item['category_id']] = $item;
}
// Next, use references to associate children with parents
foreach ($reKeyed as $id => $item) {
if (isset($item['parent'], $reKeyed[$item['parent']])) {
$reKeyed[$item['parent']]['children'][] =& $reKeyed[$id];
}
}
// Finally, go through and remove children from the outer level
foreach ($reKeyed as $id => $item) {
if (isset($item['parent'])) {
unset($reKeyed[$id]);
}
}
return $reKeyed;
}
// create menu li
function createMenuItem($item, $url){
$html = '';
$html .= '<li class="menu-item '.(!empty($item['children']) ? 'has-child' : '').'">';
$html .= '<a href="'.$url.'" class="menu-link">';
if(!empty($item['icon'])):
$html .= '<i class="'.$item['icon'].'"></i>';
endif;
$html .= $item['category_name'];
$html .= '</a>';
if(!empty($item['children'])):
$html .= createMenu($item['children'], $url);
endif;
$html .= '</li>';
return $html;
}
// menu
function createMenu($menu, $url_prefix=''){
$html = '';
$html .= '<ul class="menu">';
foreach($menu as $item):
$html .= createMenuItem($item, $url_prefix.'/'.$item['category_url']);
endforeach;
$html .= '</ul>';
return $html;
}
You can use it like so
$categories = $pdo->query('SELECT category_id, category_url, parent, category_name FROM category ORDER BY category_id');
$cat = convertToLevels($categories->fetchAll(PDO::FETCH_ASSOC));
Then in the HTML
<?= createMenu($cat); ?>
To get part of the menu example Mens Fashion, you just have to filter the $cat
array to get it. Example
$men_cat = array_values(array_filter($cat, function($val){
return strtolower($val['category_name']) === 'mens fashion';
}))[0]['children'] ?? [];
Then in the HTML
<?= createMenu($men_cat, '/mens-fashion'); ?>
QUESTION
proxy server working in one case and failed in another case
Asked 2022-Jan-23 at 14:57So i am working on eCommerce website in react and Node. coming to the point, at the time of login the proxy works totally fine but when i made get request to API it shows an error. I spent 2 days resolving this but at last came here with the hope to get the answer.
My server.js file
const express = require ( 'express');
const bodyParser = require('body-parser');
const app = express();
const {sequelize} = require('./models')
const cookieParser = require("cookie-parser");
app.use(express.json());
// app.use(express.urlencoded());
// app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ // to support URL-encoded bodies
extended: true
}));
const FarmerRoutes = require('./Routes/Farmer'); // Finished
const AdminRoutes = require('./Routes/Entities'); // Finished
const Ecommerce = require('./Routes/Ecommerce'); // Finished
const upload = require('./Controllers/ImageManagement')
app.use(cookieParser())
app.use(express.static('backend/uploads'))
app.get('/', (req, res) => {
res.send(" CattleTalk Api is active and running...")
})
app.use('/api/ecommerce',Ecommerce);
app.use('/api/admin',AdminRoutes);
app.use('/api/farmers',FarmerRoutes);
app.listen(5002,async()=>{
console.log("The app listening at 5002");
try {
await sequelize.authenticate();
console.log('Database Connection has been established successfully.');
} catch (error) {
console.error('Unable to connect to the database:', error);
}
});
My package.json at frontend looks like this
{
"name": "frontend",
"secure":false,
"version": "0.1.0",
"private": true,
"dependencies": {
"@popperjs/core": "^2.9.1",
"@testing-library/jest-dom": "^5.11.9",
"@testing-library/react": "^11.2.5",
"@testing-library/user-event": "^12.8.3",
"axios": "^0.21.1",
"bootstrap": "^5.0.2",
"formik": "^2.2.9",
"js-cookie": "^3.0.1",
"react": "^17.0.1",
"react-bootstrap": "^2.0.0-alpha.2",
"react-bootstrap-sidebar": "^0.0.1",
"react-dom": "^17.0.1",
"react-icons": "^4.2.0",
"react-router": "^5.2.0",
"react-router-bootstrap": "^0.25.0",
"react-router-dom": "^5.2.0",
"react-scripts": "4.0.3",
"web-vitals": "^1.1.1",
"yup": "^0.32.11"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"proxy": "http://localhost:5002/"
}
ANSWER
Answered 2022-Jan-23 at 14:57After hours of exploring the internet i couldn't get the answer of my problem, but debugging the code i found the problem. Actually it was one extra trailing slash in URL which made it to misbehave. I was like this before.
The correct version will be.
EXTRA NOTE: All those who have not found the solution from here should move forward to this link and look for trailing slash if found in your current URL, for making successful proxy you need to eliminate that trailing slash at the end of URL.
QUESTION
How to send previous items in cart such that my updateCart adds new items on top of previous products in cart
Asked 2022-Jan-18 at 16:03I am creating a ecommerce product cart, while adding first order it creates order with createOrder and while adding next products it runs updateCart. I have to send the previous items in the cart while running update cart because currently on adding next product it's not working.
This is my service code:
static createOrder(
order: Order,
onSuccess: Function,
onError: Function,
onFinal: Function
) {
const orderJson = serialize(Order, order)
const URL = ApiRoutes.CREATE_ORDER
axiosInstance
.post(URL, { "order": orderJson })
.then((res) => {
// const data = deserialize(Cart, res.data.order);
//onSuccess(res.data.success);
})
.catch((err) => {
onError(err);
});
}
static updateCart(
order: Order,
orderId: string,
onSuccess: Function,
onError: Function,
onFinal: Function
) {
const orderJson = serialize(Order, order)
const URL = ApiRoutes.UPDATE_CART.replace(":id", `${orderId}`)
axiosInstance
.put(URL, { "order": orderJson })
.then((res) => {
// const data = deserialize(Cart, res.data.order);
//onSuccess(res.data.success);
})
.catch((err) => {
onError(err);
});
}
This is how I am calling it:
const addToBasket = () => {
dispatch({
type: 'ADD_TO_BASKET',
item: {
"id": product.id,
"title": product.name,
"price": product.price,
"image": product.imageUrl,
},
});
// CREATE ORDER ONCE CART IS EMPTY ELSE UPDATE CART
if (props?.userCart?.orderItems?.length) {
OrderService.updateCart(
{
orderItems: [{
productId: `${product?.id}`,
quantity: 1,
// taxMode:0,
// taxPercentage:0,
//discountPercentage: ""
}]
},
props?.userCart?.id,
() => { },
() => { },
() => { },
)
} else {
OrderService.createOrder(
{
userId: user?.id,
storeId: store?.id,
orderItems: [
{
productId: `${product?.id}`,
quantity: 1,
taxMode: 0,
taxPercentage: 0,
discountPercentage: ""
}
]
},
() => { },
() => { },
() => { },
)
}
};
ANSWER
Answered 2022-Jan-18 at 16:03Just add previous products to the end of array with spread operator like ...props.userCart.orderItems
OrderService.updateCart(
{
orderItems: [{
productId: `${product?.id}`,
quantity: 1,
// taxMode:0,
// taxPercentage:0,
//discountPercentage: ""
}, ...props.userCart.orderItems]
},
props?.userCart?.id,
() => { },
() => { },
() => { },
)
}
QUESTION
useReducer: dispatch action, show state in other component and update state when action is dispatched
Asked 2022-Jan-17 at 20:44I have a problem which I can't figure it out. I'm building an ecommerce react app and using useReducer
and useContext
for state management. Client opens a product, picks number of items and then click button "Add to Cart" which dispatches an action. This part is working well, and the problem starts. I don't know how to show and update in Navbar.js
component a total number of products in cart. It is showing after route changes, but I want it to update when clicking Add to Cart button. I tried useEffect but it doesn't work.
initial state looks like this
const initialState = [
{
productName: '',
count: 0
}
]
AddToCart.js works good
import React, { useState, useContext } from 'react'
import { ItemCounterContext } from '../../App'
function AddToCart({ product }) {
const itemCounter = useContext(ItemCounterContext)
const [countItem, setCountItem] = useState(0)
const changeCount = (e) => {
if (e === '+') { setCountItem(countItem + 1) }
if (e === '-' && countItem > 0) { setCountItem(countItem - 1) }
}
return (
<div className='add margin-top-small'>
<div
className='add-counter'
onClick={(e) => changeCount(e.target.innerText)}
role='button'
>
-
</div>
<div className='add-counter'>{countItem}</div>
<div
className='add-counter'
onClick={(e) => changeCount(e.target.innerText)}
role='button'
>
+
</div>
<button
className='add-btn btnOrange'
onClick={() => itemCounter.dispatch({ type: 'addToCart', productName: product.name, count: countItem })}
>
Add to Cart
</button>
</div>
)
}
export default AddToCart
Navbar.js is where I have a problem
import React, { useContext } from 'react'
import { Link, useLocation } from 'react-router-dom'
import NavList from './NavList'
import { StoreContext, ItemCounterContext } from '../../App'
import Logo from '../Logo/Logo'
function Navbar() {
const store = useContext(StoreContext)
const itemCounter = useContext(ItemCounterContext)
const cartIcon = store[6].cart.desktop
const location = useLocation()
const path = location.pathname
const itemsSum = itemCounter.state
.map((item) => item.count)
.reduce((prev, curr) => prev + curr, 0)
const totalItemsInCart = (
<span className='navbar__elements-sum'>
{itemsSum}
</span>
)
return (
<div className={`navbar ${path === '/' ? 'navTransparent' : 'navBlack'}`}>
<nav className='navbar__elements'>
<Logo />
<NavList />
<Link className='link' to='/cart'>
<img className='navbar__elements-cart' src={cartIcon} alt='AUDIOPHILE CART ICON' />
{itemsSum > 0 ? totalItemsInCart : null}
</Link>
</nav>
</div>
)
}
export default Navbar
ANSWER
Answered 2022-Jan-14 at 17:06Well, ItemCounterContext is important for this problem, just ignore StoreContext, it's for images... Here is a reducer function.
export const reducer = (state, action) => {
// returns -1 if product doesn't exist
const indexOfProductInCart = state.findIndex((item) => item.productName === action.productName)
const newState = state
switch (action.type) {
case 'increment': {
if (indexOfProductInCart === -1) {
newState[state.length] = { productName: action.productName, count: state.count + 1 }
return newState
}
newState[indexOfProductInCart] = { productName: action.productName, count: state.count + 1 }
return newState
}
case 'decrement': {
if (indexOfProductInCart === -1) {
newState[state.length] = { productName: action.productName, count: state.count - 1 }
return newState
}
newState[indexOfProductInCart] = { productName: action.productName, count: state.count - 1 }
return newState
}
case 'addToCart': {
if (indexOfProductInCart === -1) {
newState[state.length] = { productName: action.productName, count: action.count }
return newState
}
newState[indexOfProductInCart] = { productName: action.productName, count: action.count }
return newState
}
case 'remove': return state.splice(indexOfProductInCart, 1)
default: return state
}
}
And here is App.js where I share state to other components
import React, { createContext, useMemo, useReducer } from 'react'
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom'
import Navbar from './components/Navbar/Navbar'
import Homepage from './pages/Homepage/Homepage'
import Footer from './components/Footer/Footer'
import ErrorPage from './pages/ErrorPage/ErrorPage'
import SelectedCategory from './pages/SelectedCategory/SelectedCategory'
import SingleProduct from './pages/SingleProduct/SingleProduct'
import ScrollToTop from './services/ScrollToTop'
import store from './services/data.json'
import { reducer } from './services/ItemCounter'
import './scss/main.scss'
export const StoreContext = createContext(store)
export const ItemCounterContext = createContext()
function App() {
const initialState = [{ productName: '', count: 0 }]
const [state, dispatch] = useReducer(reducer, initialState)
const counter = useMemo(() => ({ state, dispatch }), [])
return (
<div className='app'>
<StoreContext.Provider value={store}>
<ItemCounterContext.Provider value={counter}>
<Router>
<ScrollToTop />
<Navbar />
<Routes>
<Route path='/' element={<Homepage />} />
<Route path='/:selectedCategory' element={<SelectedCategory />} />
<Route path='/:selectedCategory/:singleProduct' element={<SingleProduct />} />
<Route path='*' element={<ErrorPage />} />
</Routes>
<Footer />
</Router>
</ItemCounterContext.Provider>
</StoreContext.Provider>
</div>
)
}
export default App
QUESTION
connect spring boot to swagger
Asked 2022-Jan-05 at 20:10I am trying to connect my e-commerce project backend to swagger2. I have installed all the dependencies, yet I still cannot do it.
This is the dependency declared in my pom.xml file:
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
This is one of my user controller files:
@RestController
@RequestMapping("/api")
@CrossOrigin
public class UserController {
@Autowired
private UserRepository userRepository;
@GetMapping("/")
public List<User> GetUsers() {
return userRepository.findAll();
}
@GetMapping("/{id}")
public User GetUser(@PathVariable String id) {
return userRepository.findById(id).orElse(null);
}
@PostMapping("/")
public User postMethodName(@RequestBody User user) {
return userRepository.save(user);
}
@PutMapping("/")
public User PutMapping(@RequestBody User newUser) {
User oldUser = userRepository.findById(newUser.getId()).orElse(null);
oldUser.setName(newUser.getName());
oldUser.setEmail(newUser.getEmail());
oldUser.setPassword(newUser.getPassword());
userRepository.save(oldUser);
return oldUser;
}
@DeleteMapping("/{id}")
public String DeleteUser(@PathVariable String id) {
userRepository.deleteById(id);
return id;
}
}
This is the code of my main application:
package com.omazon.ecommerce;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@SpringBootApplication
@EnableSwagger2
public class ECommerceApplication {
public static void main(String[] args) {
SpringApplication.run(ECommerceApplication.class, args);
}
}
Lastly, this is what I declared in the application.properties
file:
spring.data.mongodb.uri=mongodb://localhost:27017/e-commerce
This is the picture of the error I got:
ANSWER
Answered 2022-Jan-05 at 20:10Swagger2's usage seems to require (or at least often includes) the concept of a Docket
api via an instantiation such as new Docket()
or new Docket(DocumentationType.SWAGGER_2)
. I don't see that in your code snippets, so wonder if that may be one issue.
Per the swagger docs, Docket
is Springfox’s primary api configuration mechanism.
Specifically, this section regarding configuration may be helpful. Note the Docket
instantiation:
...
@Bean //Don't forget the @Bean annotation
public Docket customImplementation(){
return new Docket()
.apiInfo(apiInfo());
//... more options available
...
QUESTION
Can Django select_for_update be used to acquire a read lock?
Asked 2021-Dec-08 at 04:47I'm working on a project similar to ecommerce in which I have models that represent a product with a certain amount in the storage, and users can buy some quantity of the product as long as it doesn't exceed the stored amount. I want to avoid a race condition taking place when the server receives multiple requests to buy the same product.
class Product(models.Model):
amount_in_storage = models.PositiveIntegerField() # for design reasons, this amount is unchangeable, it must be only evaluated once during initialization like constants in C++
@property
def amount_available_for_purchase(self):
return self.amount_in_storage - Purchase.objects.filter(product=self.id).aggregate(models.Sum('amount'))["sum__amount"]
class Purchase(models.Model):
product = models.ForeignKey(Product, ...)
amount = models.PositiveIntegerField()
payment_method = ...
Let's assume that this is the block of code that's responsible for creating a purchase.
@atomic_transaction
def func(product_id, amount_to_purchase):
product = Product.objects.get(...)
if product.amount_available_for_purchase > amount_to_purchase:
# do payment related stuff
Purchase.objects.create(product=product, amount=amount_to_purchase)
# do more stuff
I would like to restrict concurrent access to this block of code, Ideally I would like to obtain a read
lock access at the if
condition, so that if multiple threads try to see if the amount available is greater than the amount to purchase, one of the threads will have to wait until the transaction is done, and then the read request will be evaluated, so I thought leveraging Django's select_for_update
and a version
field like so:
class Product(models.Model):
amount_in_storage = models.PositiveIntegerField()
version = models.PositiveIntegerField() # we use this field just to write to it, no reading will take place
@property
def amount_available_for_purchase(self):
return self.amount_in_storage - Purchase.objects.filter(product=self.id).aggregate(models.Sum('amount'))["sum__amount"]
And I use this field to obtain a lock like so:
@atomic_transaction
def func(product_id, amount_to_purchase):
product = Product.objects.select_for_update.get(...)
# acquiring a lock
product.version += 1
product.save()
if product.amount_available_for_purchase > amount_to_purchase:
# do payment related stuff
Purchase.objects.create(product=product, amount=amount_to_purchase)
# do more stuff
Using select_for_update
if multiple threads reach the version modification line, only the first will evaluate, and the rest will have to wait until the whole transaction is completed, hence acquiring a read lock for the line at the if condition. In other words, only 1 thread at a time will have access to this block of code.
My questions are:
ANSWER
Answered 2021-Dec-08 at 04:47Yes, your approach is pretty much right and it will acquire the lock for the first query and the rest will have to wait until the transaction is complete.
If you are not using the version field for anything other than acquiring the lock, you can forcefully acquire a lock by forcefully evaluating the QuerySet using a list()
. See the code below.
@atomic_transaction
def func(product_id, amount_to_purchase):
# Forcefully acquiring a lock
product = list(Product.objects.select_for_update.filter(...))[0]
if product.amount_available_for_purchase > amount_to_purchase:
# do payment related stuff
Purchase.objects.create(product=product, amount=amount_to_purchase)
# do more stuff
Here you are acquiring the lock forcefully by evaluating the QuerySet like mentioned here in the docs.
QUESTION
Google Tag Manager / Enhanced E-commerce - Purchase tag dataLayer push working only on Tag Assistance
Asked 2021-Dec-07 at 07:30I'm trying to add Enhance Ecommerce but something isn't okay. When I make an order through Google Tag Assistance everything is working and the transaction is showed on the Google Analytics but when I make an order normally like customer nothing is showed.
This is what I've added to thank-you page on the shop
<script type="text/javascript">
dataLayer.push({ ecommerce: null });
dataLayer.push({
'event': 'transaction',
'ecommerce': {
'purchase': {
'actionField': {
'id': '<?php echo $order->get_order_number() ?>',
'revenue': '<?php echo number_format($order->get_subtotal(), 2, ".", ""); ?>',
'number_of_products': '<?php echo $order->get_item_count(); ?>'
},
'products': [
<?php foreach ($order->get_items() as $key => $item): ?>
{
'name': '<?php echo $item['name']; ?>',
'id': '<?php echo $item['product_id']; ?>',
'price': '<?php echo number_format($item->get_total(), 2, ".", ""); ?>',
'quantity': '<?php echo $item['qty']; ?>'
},
<?php endforeach;
?>
]
}
}
});
</script>
And this is my setup in Google Tag Manager
Tried google, tried tutorials and still nothing helped.
When I run from Tag Assistant everything is go to analytic. When doesn't go through Tag Assistant nothing is showed.
Any ideas?
UPDATE: GTM Workspace preview
ANSWER
Answered 2021-Dec-07 at 07:26In order to enter preview, you have to first open GTM. In GTM, you have workspaces. Or at least, the default one. open GTM, go to the overview tab of the workspace that you're previewing (since you don't know what worspaces are, you probably use the default one) and make sure there are no Workspace Changes in it. Here is a screenshot of a workspace WITH changes:
And here is another workspace with NO changes:
If you have changes in your workspace, try publishing them and see if your tags start firing in prod.
Community Discussions, Code Snippets contain sources that include Stack Exchange Network
No vulnerabilities reported
Save this library and start creating your kit
Share this Page
15 best Python Bitcoin Wallet
See all related Kits
saleor
by mirumee
reaction
by reactioncommerce
spree
by spree
magento2
by magento
nopCommerce
by nopSolutions
See all Ecommerce Libraries
saleor
by mirumee
magento2
by magento
spree
by spree
PrestaShop
by PrestaShop
shopizer
by shopizer-ecommerce
See all Ecommerce Libraries
Save this library and start creating your kit