Got a parsing error while assign a value on my state - reactjs

Hi friends,
I'm getting a little trouble putting that to work.
This method intend to put check if there's a product in the cart, if true, sum the same product.
onAddProductToCart = (productId) => {
const productInCart = this.state.productsInCart.find(
(product) => productId === product.id
);
if (productInCart) {
const newProductsInCart = this.state.productsInCart.map(product => {
if(productId === product.id) {
return {
...product,
quantity = product.quantity + 1
}
}
return product
})
this.setState({productsInCart: newProductsInCart})
}
};
I'm getting this error point to my assignment "=" bellow
Parsing error unexpected token:
quantity = product.quantity + 1
This method is inside the App class component , with has some mocked data.
class App extends Component {
state = {
minFilter: "100",
maxFilter: "2000",
nameFilter: "Produto",
productsInCart: [
{
id: 3,
name: "Produto 3",
price: 300.77,
photo: "https://picsum.photos/200/200?a=3",
quantity: 1,
},
{
id: 4,
name: "Produto 4",
price: 400,
photo: "https://picsum.photos/200/200?a=4",
quantity: 2,
},
],
};

You have to use colon : when set a object property
return {
...product,
quantity:product.quantity + 1
}

Using a colon would do the trick
quantity: product.quantity + 1

Related

find a specifik obejct with arrays and print it out, react

I want to use find when clicking a button, I want to find an obejct (working in react)
let numbers = [
{ id: 0, namn: one, img: "../number/one" },
{ id: 1, namn: two, img: "../number/two" },
{ id: 2, namn: three, img: "../number/three" },
];
const [selected, setSelected] = useState({
id: 0,
name: "one",
img: "../number/one",
});
const count = useRef(0);
function next() {
if (count.current === 2) {
count.current = 0;
let found = numbers.find((number) => number.id === count.current);
} else {
count.current = count.current + 1;
let foundtwo = numbers.find((number) => number.id === count.current);
}
return (
<>
<img>{selected.img}</img>
namn: {selected.name}
</>
);
}
I can find it but I want to put it in a useState.
or somehow get it to show. how can I get found, and found two out in the return
the awswer was to put a
if( found === undefined){
console.log("error")
}else{
setSelected(found)
}

React update item quantity in the shopping cart

I'm trying to update the quantity of each item , i have tried my code but it didn't work correctly, but when i tried a solution found here: How to update item quantity in the shopping cart using React Redux , it worked thankfully .
But i want to understand why my code didn't work (i'm using useContext not redux but normally that has nothing to do with the problem )
**Code that worked : ** :
cartItems: state.cartItems.map(item => item.id === payload.id
? {
...item,
qty: item.qty + 1,
}
: item
),
**My unfunctional code : **
if (productsInCard.find((x) => x.name === e.name)) {
let qu ; //to get the new quantity
const arr = [...productsInCard];
productsInCard.forEach((ele, index) => {
if (ele.name === e.name) {
qu = ele.quantity + 1;
console.log(ele.quantity + " this is the quantity before +1")
arr.splice(index, 1);
addCard(arr);
console.log("old item deleted" + JSON.stringify(arr))
addCard([
...productsInCard,
{
name: e.name,
price: e.price,
image: e.images[0],
quantity: qu,
},
]);
addCard([
...productsInCard,
{
name: e.name,
price: e.price,
image: e.images[0],
quantity: qu,
},
]);
console.log(" item + quantity added : " + JSON.stringify(productsInCard));
}
});
const newArr = [...productsInCard]
productsInCard.forEach((ele, index)=>{
if(ele.name === e.name){
console.log(ele.quantity)
if (ele.quantity < qu)
newArr.splice(index, 1)
addCard(newArr);
}
})
} else {
addCard([
...productsInCard,
{
name: e.name,
price: e.price,
image: e.images[0],
quantity: 1,
},
]);
console.log("list with new item : " + productsInCard);
}
}

need to implement Undo function using react hooks

need to implement undo function in a state array data. i remove the data by id using filter method but i need to restore the data after click on undo button. how to implement in React Hooks?
const [dataSource, setDatasource] = useState([
{
id: 1,
name: 'john',
gender: 'm'
},
{
id: 2,
name: 'mary',
gender: 'f'
},
{
id: 3,
name: 'loki',
gender: 'M'
},
{
id: 4,
name: 'Thor',
gender: 'M'
},
]);
You will have to keep track of all the actions that the user performs, and calculate the end result from that. When a user clicks "undo", you can just remove the latest action.
const actions = [
{
operation: "create",
name: "Some name",
index: 1
},
{
operation: "delete",
index: 1
}
];
const state = (() => {
let appliedState = [];
for (const action of actions) {
if (action.operation === "create") {
appliedState .push(action.name);
} else if (action.operation === "delete") {
appliedState = appliedState .filter(currentState => currentState.index !== action.index);
}
}
return appliedState ;
})();
You can see a working react example here.

Replacing value in nested state with react functional components

I am trying to use update state in a react function component but it is not working. I tried following a tutorial on pluralsite and apply it to my own project. Ideally this code should be finding the product based on the ID number and replacing the total with a new value.
Unfortunately I am getting an error saying that 'productData.find' is not a function and I'm not sure where the code being used for that is. Are there any suggestions on how to solve this issue?
This is what the data looks like. In this example I am saving the first element of the array.
export let data = [
{
name: "Name",
description:
"",
products: [
{
id: 1,
name: "Name 1",
material: 1.05,
time: 25,
total: 0,
},
{
id: 2,
name: "Name 2",
material: 3,
time: 252,
total: 0,
},
],
},
...
];
function CompareCard({}) {
const index = 0;
const [productData, setProductData] = useState(data[index]);
function setTotalUpdate(id) {
const productPrevious = productData.find(function (rec) {
return rec.id === id;
});
const productUpdated = {
...productPrevious,
total: 1,
};
const productNew = productData.map(function (rec) {
return rec.id === id ? productUpdated : rec;
});
setProductData(productNew);
}
setTotalUpdate(1)
}
It's because productData is not an array so .find would not work. You want iterate over the products property in your data, so do productData.products.find(...)
When you do
const [productData, setProductData] = useState(data[index])
you don't pass an Array on your state but an Object (the first element of your data so an Object) and Object don't have find method.
Try
const [productData, setProductData] = useState([data[index]])
with [] on our useState to put your Object on array
///////////////////////////////// Edit /////////////
Ok, I try your code, and I propose you this.
import React, { useState } from "react";
const data = [
{
name: "Name",
description: "",
products: [
{
id: 1,
name: "Name 1",
material: 1.05,
time: 25,
total: 0,
},
{
id: 2,
name: "Name 2",
material: 3,
time: 252,
total: 0,
},
],
},
];
const CompareCard = () => {
// setState with the subArray products from data[0], I use '...' (spread operator) inside a Array or an Object to make a shalow copy
const [productsData, setProductsData] = useState([...data[0].products]);
const setTotalUpdate = (id) => {
// find the product to change inside products collection, that's ok
const productPrevious = productsData.find((rec) => {
return rec.id === id;
});
// create a new product to change one property's value, you can do something like 'productPrevious.total = 1', same same
const productUpdated = {
...productPrevious,
total: 1,
};
// create a new products collection to update state
const productNew = productsData.map((rec) => {
return rec.id === id ? productUpdated : rec;
});
setProductsData([...productNew]);
};
const setTotalUpdateSecond = (id) => {
// create a newState
const newState = productsData.map((product) => {
// condition if id === productId and do something
if (id === product.id) {
product.total = 1;
}
// both case, I return the product (change or not)
return product;
});
setProductsData([...newState]);
};
return (
<>
<button onClick={() => setTotalUpdate(1)}>Test old method on product 1</button>
<button onClick={() => setTotalUpdateSecond(2)}>Test second method on product 2</button>
{productsData.map((product) => {
return (
<>
<p>Product Id : {product.id} / Product Total : {product.total}</p>
</>
);
})}
</>
);
};
export default CompareCard;
Can you copy / past this, try and say me if it's what you want, if yes, I explain you where the confusion was. If not, explain me, what's the problem here and I modificate.

Update state that depends on other calculated state in React-Hooks

I want to update a state (data) that depends on other calculated state (server)
setServer(prevTweets =>
[...json, ...prevTweets].filter(
(e, i, arr) => i === arr.findIndex(t => t.tweetId === e.tweetId)
)
)
The data above will be used to set the state below (data) :
let totalPositive = 0;
let totalNegative = 0;
let totalNeutral = 0;
server.forEach(tweet => {
if(tweet.sentiment >0) totalPositive++;
if(tweet.sentiment < 0) totalNegative++;
if(tweet.sentiment ===0) totalNeutral++;
})
setData([
{ name: 'Positive', value: totalPositive },
{ name: 'Negative', value: totalNegative },
{ name: 'Neutral', value: totalNeutral },
])
Since it's asynchronous, the setData operation is always late. I know that I can use useEffect but apparently it will make an infinite loop and it's not right to use it in this case.
If you set the new data before you set the server you'd skip one render:
//still defaults to server so if you do't pass anything it;s still the same
const setNewData = (newServer = server) => {
const [
totalPositive,
totalNegative,
totalNeutral,
] = newServer.reduce(
([pos, neg, neu], { sentiment }) =>
sentiment > 0
? [pos + 1, neg, neu]
: sentiment < 0
? [pos, neg + 1, neu]
: [pos, neg, neu + 1],
[0, 0, 0]
);
setData([
{ name: 'Positive', value: totalPositive },
{ name: 'Negative', value: totalNegative },
{ name: 'Neutral', value: totalNeutral },
]);
};
setServer(prevTweets => {
const newServer = uniqueByTweetId([
...json,
...prevTweets,
]);
setNewData(newServer);
return newServer;
});
Unrelated to the question but could be important is that the way you get unique values could be improved. You could get unique values in one pass without having to call find index many times:
const uniqueBy = getter => arr => {
const items = new Map();
return arr.filter(item => {
const key = getter(item);
const ret = items.get(key);
items.set(key,true);
return !ret;
});
};
const data = [
{ id: 1 },
{ id: 2 },
{ id: 3 },
{ id: 4 },
{ id: 5 },
{ id: 1 },
{ id: 7 },
{ id: 1 },
{ id: 7 },
{ id: 8 },
{ id: 1 },
];
const uniqueById = uniqueBy(i => i.id);
console.log(uniqueById(data));

Resources