how can I pass data that is calculated in one component to another component on different page?
Problem Description:
I have one component in which I calculate price based on model and extras that go with it. it looks like this:
product.jsx:
const name = productData.name;
const modelPrice = productData.modelPrice; {/*Array that must contain: [key: number, model: string, price: number] */}
{/*NewExtras START */}
const extrasList = productData.extras; {/*Array that must contain: [ key: number, name: string, price: number, active: boolean (default: false) ] */}
const [extrasListP, setExtrasListP] = useState(extrasList);
const toggleExtras = (extra) => {
const updatedExtrasList = extrasListP.map((ex) => {
extra.name === ex.name ? ex.active = !ex.active : ex.active = ex.active;
return ex;
});
setExtrasListP(updatedExtrasList);
};
const activeExtras = extrasListP.filter((extra) => {
return extra.active;
});
const aExtrasList = activeExtras.map((extra) => {
return (
<div key={extra.key}>{extra.name}, </div>
);
})
const sumExtras = activeExtras.reduce((previousValue, object) => {
return previousValue + object.price;
}, 0);
{/*NewExtras END */}
const [quantity, setQuantity] = useState(1);
{/*Model variables START */}
const [activeModel, setActiveModel] = useState(modelPrice[0].model);
const [activePrice, setActivePrice] = useState(modelPrice[0].price);
const modelPriceList = modelPrice.map((item) => {
return (
<div
key = {item.key}
className={ activePrice === item.price ? styles.activeModelItem : styles.modelItem}
onClick={() => {setActiveModel(item.model); setActivePrice(item.price)}}
>
| {item.model} |
</div>
);
});
{/*Model variables END */}
const [buttonText, setButtonText] = useState("Dodaj u korpu");
const finalPrice = (activePrice + sumExtras) * quantity;
const [korpa, setKorpa] = useState([]);
const toSend = <>proizvod: {name} - Model: {activeModel} - Dodatno: - {aExtrasList} - Količina: {quantity} - Ukupno: {finalPrice}</>;
I want to create component called Cart.jsx to which I will send: toSend variable.
I also want it to stay chached so it stays when user refreshes page.
I was searching the internet for week and a half now and cant seem to find suitable answer for my situation. I hope that somebody will at least point me at right direction.
Solution – 1
You can do all of your calculations on the parent component and then assign that to a state hook. You can then pass that as props to the Cart.jsx component. Whenever you run your function to add to the total you can update a total state, then when you want to pass it to the cart you can via props.
const [total, setTotal] = useState(0);
const addTotalSum = () => {
// Logic here for getting the total.
setTotal(); // Set the returned total value here
}
...
<Cart totalVal={total} /> // Pass total into Cart component as props and then access it in the Cart with props.totalVal
Solution – 2
If you want to pass data from one page to another page, then these are the ways:
- pass data via state while routing
// react route v5
history.push("path", {state: yourdata})
// react router v6
navigate("path", {state: yourdata})
- Pass data in query string while routing
const queryString = `data=${JSON.stringify(yourdata)}`;
// attach above query in route path like this:
// react route v5
history.push(`path?${queryString}`, {state: yourdata})
// react router v6
navigate(`path?${queryString}`, {state: yourdata})
- Set data in local storage or session storage and access on next page.
const stringifyData = JSON.stringify(yourData);
localStorage.set("yourkey", stringifyData);
// Now access data on next page
JSON.parse(localStorage.get("yourKey"));
In your case, you want to persist data. So option 3 will suit your use case