Buttons displaying both times - javascript

The issue is lying in my Sean Connery and Roger Moore list of movies buttons. When I click on Sean Connery List of Movies, it displays Connery movies on Roger Moore's list too, and vice versa.
Prettier 2.7.1
Playground link
--parser babel
Input:
import React, { useState } from "react";
import styled from "styled-components";
import axios from "axios";
const Button = styled.button`
background-color: black;
color: white;
font-size: 20px;
padding: 10px 60px;
border-radius: 5px;
margin: 10px 0px;
cursor: pointer;
`;
function ButtonClick() {
const [users, setUsers] = useState();
const fetchData = (type) => {
axios
.get(
"https://iznfqs92n3.execute-api.us-west-1.amazonaws.com/dev/api/v2/movies"
)
.then((response) => {
console.log(response.data)
const mappedArray = response.data
.map(
(item) =>
item[type] ||
(type === "directors" && item.director) ||
(type === "title_song" && item.title_song) ||
(type === "movie_year" && item.movie_year)
)
.filter((uniqueVal) => uniqueVal);
setUsers({ [type]: Array.from([...new Set(mappedArray)]) });
// console.log(movies)
});
};
const [movies, setMovies] = useState();
const fetchMovieData = (name) => {
axios
.get(
"https://iznfqs92n3.execute-api.us-west-1.amazonaws.com/dev/api/v2/movies"
).then(response => {
console.log(response.data)
setMovies(response.data.filter(item => item.bond_actor === name).map(item => item.movie_title));
console.log("Hello World")
console.log("Hello World")
// console.log()
})
};
return (
<div>
<div>
<h2>Bond Database</h2>
<h5>
Click on the buttons to see the list of all the bond movie's
directors, bond actors, release year, and title songs
</h5>
<Button onClick={() => fetchData("bond_actor")}>Bond Actors</Button>
{users && (
<ul>
{users?.bond_actor?.map((user, index) => (
<li key={index}>
<a href="https://iznfqs92n3.execute-api.us-west-1.amazonaws.com/dev/api/v2/movies">
{user}
</a>
</li>
))}
</ul>
)}
</div>
<div>
<Button onClick={() => fetchData("directors")}>Directors</Button>
{users && (
<ul>
{users?.directors?.map((director) => (
<li key={director}>{director}</li>
))}
</ul>
)}
</div>
<div>
<Button onClick={() => fetchData("title_song")}>Songs</Button>
{users && (
<ul>
{users?.title_song?.map((title_song) => (
<li key={title_song}>{title_song}</li>
))}
</ul>
)}
</div>
<div>
<Button onClick={() => fetchData("movie_year")}>Movie Year</Button>
{users && (
<ul>
{users?.movie_year?.map((movie_year) => (
<li key={movie_year}>{movie_year}</li>
))}
</ul>
)}
</div>
<div>
<Button onClick={() => fetchMovieData("Sean Connery")}>Sean Connery's List of Movies</Button>
{movies && (
// console.log(movies),
<ul>
{movies?.map((movie) => (
// console.log(movie),
<li key={movie}>{movie}</li>
))}
</ul>
)
}
</div>
<div>
<Button onClick={() => fetchMovieData("Roger Moore")}>Roger Moore List of Movies</Button>
{movies && (
<ul>
{movies?.map((movie) => (
// console.log(moviesR),
<li key={movie}>{movie}</li>
))}
</ul>
)}
</div>
</div>
);
}
export default ButtonClick;
I'd assume the issue is that both buttons are using the same state, but since the names have spaces, I don't know how to create different states for the two buttons. If I get some assistance on this, it would be much appreciated.

You can follow this:
import React, { useState } from "react";
import styled from "styled-components";
import axios from "axios";
const Button = styled.button`
background-color: black;
color: white;
font-size: 20px;
padding: 10px 60px;
border-radius: 5px;
margin: 10px 0px;
cursor: pointer;
`;
function ButtonClick() {
const [users, setUsers] = useState();
const fetchData = (type) => {
axios
.get(
"https://iznfqs92n3.execute-api.us-west-1.amazonaws.com/dev/api/v2/movies"
)
.then((response) => {
console.log(response.data);
const mappedArray = response.data
.map(
(item) =>
item[type] ||
(type === "directors" && item.director) ||
(type === "title_song" && item.title_song) ||
(type === "movie_year" && item.movie_year)
)
.filter((uniqueVal) => uniqueVal);
setUsers({ [type]: Array.from([...new Set(mappedArray)]) });
// console.log(movies)
});
};
const [movies, setMovies] = useState({});
const fetchMovieData = (name) => {
axios
.get(
"https://iznfqs92n3.execute-api.us-west-1.amazonaws.com/dev/api/v2/movies"
)
.then((response) => {
console.log(response.data);
setMovies({
[name]: response.data
.filter((item) => item.bond_actor === name)
.map((item) => item.movie_title)
});
console.log("Hello World");
console.log("Hello World");
// console.log()
});
};
return (
<div>
<div>
<h2>Bond Database</h2>
<h5>
Click on the buttons to see the list of all the bond movie's
directors, bond actors, release year, and title songs
</h5>
<Button onClick={() => fetchData("bond_actor")}>Bond Actors</Button>
{users && (
<ul>
{users?.bond_actor?.map((user, index) => (
<li key={index}>
<a href="https://iznfqs92n3.execute-api.us-west-1.amazonaws.com/dev/api/v2/movies">
{user}
</a>
</li>
))}
</ul>
)}
</div>
<div>
<Button onClick={() => fetchData("directors")}>Directors</Button>
{users && (
<ul>
{users?.directors?.map((director) => (
<li key={director}>{director}</li>
))}
</ul>
)}
</div>
<div>
<Button onClick={() => fetchData("title_song")}>Songs</Button>
{users && (
<ul>
{users?.title_song?.map((title_song) => (
<li key={title_song}>{title_song}</li>
))}
</ul>
)}
</div>
<div>
<Button onClick={() => fetchData("movie_year")}>Movie Year</Button>
{users && (
<ul>
{users?.movie_year?.map((movie_year) => (
<li key={movie_year}>{movie_year}</li>
))}
</ul>
)}
</div>
<div>
<Button onClick={() => fetchMovieData("Sean Connery")}>
Sean Connery's List of Movies
</Button>
{movies && (
// console.log(movies),
<ul>
{movies?.["Sean Connery"]?.map((movie) => (
// console.log(movie),
<li key={movie}>{movie}</li>
))}
</ul>
)}
</div>
<div>
<Button onClick={() => fetchMovieData("Roger Moore")}>
Roger Moore List of Movies
</Button>
{movies && (
<ul>
{movies?.["Roger Moore"]?.map((movie) => (
// console.log(moviesR),
<li key={movie}>{movie}</li>
))}
</ul>
)}
</div>
</div>
);
}
export default ButtonClick;

This is so because you are using single state, movies to show movies under both sections.
<ul>
{movies?.map((movie) => (
// console.log(moviesR),
<li key={movie}>{movie}</li>
))}
</ul>
This is common to both sections, and this only checks whether movies have any value or not.
This issue can be solved by creating different states for different movie collections.

One way of handling this is to take a reducer approach:
const [movies, setMovies] = useState({});
const fetchMovieData = (name) => {
axios
.get(
"..."
).then(response => {
...
const newMoviesState = {...movies};
newMoviesState[name] = response.data.filter(item => item.bond_actor === name).map(item => item.movie_title)
setMovies(newMoviesState);
...
})
};
Then, in your JSX for the buttons and lists:
<div>
<Button onClick={() => fetchMovieData("Sean Connery")}>Sean Connery's List of Movies</Button>
{movies["Sean Connery"]?.length && (
...
<ul>
{movies["Sean Connery"].map((movie) => (
...
<li key={movie}>{movie}</li>
))}
</ul>
)
}
</div>

found a simple way to do it.
import React, { useState } from "react";
import styled from "styled-components";
import axios from "axios";
const Button = styled.button`
background-color: black;
color: white;
font-size: 20px;
padding: 10px 60px;
border-radius: 5px;
margin: 10px 0px;
cursor: pointer;
`;
function ButtonClick() {
const [users, setUsers] = useState();
const fetchData = (type) => {
axios
.get(
"https://iznfqs92n3.execute-api.us-west-1.amazonaws.com/dev/api/v2/movies"
)
.then((response) => {
console.log(response.data)
const mappedArray = response.data
.map(
(item) =>
item[type] ||
(type === "directors" && item.director) ||
(type === "title_song" && item.title_song) ||
(type === "movie_year" && item.movie_year)
)
.filter((uniqueVal) => uniqueVal);
setUsers({ [type]: Array.from([...new Set(mappedArray)]) });
// console.log(movies)
});
};
const [movies, setMovies] = useState({sean:[], roger: []});
const fetchMovieData = (name, key) => {
axios
.get(
"https://iznfqs92n3.execute-api.us-west-1.amazonaws.com/dev/api/v2/movies"
).then(response => {
console.log(response.data)
setMovies({...movies,[key]:response.data.filter(item => item.bond_actor === name).map(item => item.movie_title)});
console.log("Hello World")
console.log("Hello World")
console.log(movies)
})
};
return (
<div>
<div>
<h2>Bond Database</h2>
<h5>
Click on the buttons to see the list of all the bond movie's
directors, bond actors, release year, and title songs
</h5>
<Button onClick={() => fetchData("bond_actor")}>Bond Actors</Button>
{users && (
<ul>
{users?.bond_actor?.map((user, index) => (
<li key={index}>
<a href="https://iznfqs92n3.execute-api.us-west-1.amazonaws.com/dev/api/v2/movies">
{user}
</a>
</li>
))}
</ul>
)}
</div>
<div>
<Button onClick={() => fetchData("directors")}>Directors</Button>
{users && (
<ul>
{users?.directors?.map((director) => (
<li key={director}>{director}</li>
))}
</ul>
)}
</div>
<div>
<Button onClick={() => fetchData("title_song")}>Songs</Button>
{users && (
<ul>
{users?.title_song?.map((title_song) => (
<li key={title_song}>{title_song}</li>
))}
</ul>
)}
</div>
<div>
<Button onClick={() => fetchData("movie_year")}>Movie Year</Button>
{users && (
<ul>
{users?.movie_year?.map((movie_year) => (
<li key={movie_year}>{movie_year}</li>
))}
</ul>
)}
</div>
<div>
<Button onClick={() => fetchMovieData("Sean Connery", "sean")}>Sean Connery's List of Movies</Button>
{movies && movies.sean && (
// console.log(movies),
<ul>
{movies?.sean?.map((movie) => (
// console.log(movie),
<li key={movie}>{movie}</li>
))}
</ul>
)
}
</div>
<div>
<Button onClick={() => fetchMovieData("Roger Moore", "roger")}>Roger Moore List of Movies</Button>
{movies && movies.roger && (
<ul>
{movies?.roger?.map((movie) => (
// console.log(moviesR),
<li key={movie}>{movie}</li>
))}
</ul>
)}
</div>
</div>
);
}
export default ButtonClick;
you can simply pass a key and make sub arrays for each actor
if u can use key map object it will be less confusing.
ex:
const actors = {
sean: "Sean Connery",
roger: "Roger Moore"
}

Related

react-paypal-js not changing currency

function App() {
return (
<PayPalScriptProvider
options={{
"client-id": process.env.REACT_APP_PAYPAL_CLIENT_ID,
currency: "PHP",
}}
>
<Router>
<div className="app">
<Routes>
<Route path="/" element={<LandingPage />}></Route>
<Route path="/admin" element={<Admin />}></Route>
</Routes>
</div>
</Router>
</PayPalScriptProvider>
);
}
I specified the currency in the properties of paypal script provider but it's still in usd
Purchase Image showing USD
What should I do to change the currency of it to Philippine Peso
Here is the link of the npm package that i used:
https://www.npmjs.com/package/#paypal/react-paypal-js
Whole Code
import "./App.css";
import { useState, useRef, useEffect } from "react";
import Dropzone from "react-dropzone";
import { PayPalButtons, PayPalScriptProvider } from "#paypal/react-paypal-js";
import {
arrayUnion,
collection,
deleteDoc,
doc,
onSnapshot,
orderBy,
query,
serverTimestamp,
setDoc,
updateDoc,
} from "firebase/firestore";
import { db, storage } from "./firebase.js";
import { v4 as uuidv4 } from "uuid";
import { getDownloadURL, ref, uploadString } from "firebase/storage";
import { BrowserRouter as Router, Routes, Route } from "react-router-dom";
import thanks from "./Images/thanks.png";
function PaypalCheckoutButton(props) {
const [error, setError] = useState(null);
const handleApprove = (orderID) => {
props.completeOrder();
};
if (error) {
alert(error);
}
return (
<div style={{ marginTop: "1rem" }}>
<PayPalButtons
createOrder={(data, actions) => {
return actions.order.create({
purchase_units: [
{
description: props.product.description,
amount: {
currency_code: "PHP",
value: props.product.price,
},
},
],
});
}}
onApprove={async (data, action) => {
const order = await action.order.capture();
console.log("order", order);
handleApprove(data.orderID);
}}
onCancel={() => {}}
onError={(err) => {
setError(err);
console.log("Paypal Checkout Error", err);
}}
/>
</div>
);
}
function Step1(props) {
const [isGift, setIsGift] = useState(null);
const [message, setMessage] = useState("");
function newKeychain() {
setIsGift(null);
props.setOrders((currentOrders) => [
{ image: props.image, message: message },
...currentOrders,
]);
props.setImage(null);
}
function handleShowButton() {
if (isGift === false) {
return props.image;
} else if (isGift === true) {
return props.image && message !== "";
}
}
return (
<div
className="step1 step"
style={isGift === true ? { marginTop: "5rem" } : {}}
>
{isGift === null && (
<>
<h1 className="title">Choose what type of keychain</h1>
<div className="purchaseTypeSection">
<div
className="formyself purchaseType"
onClick={() => setIsGift(false)}
>
<h2>Standard</h2>
<p className="keychainTypeDescription">
Perfect for personal use
</p>
<h2 className="price">₱69</h2>
</div>
<div className="gift purchaseType" onClick={() => setIsGift(true)}>
<h2>With Message</h2>
<p className="keychainTypeDescription">
Perfect for gifts to your love ones
</p>
<h2 className="price">₱99</h2>
</div>
</div>
</>
)}
{isGift !== null && (
<>
<h1 className="title">Choose your image</h1>
<Dropzone
onDrop={(acceptedFiles) =>
props.setImage(() => {
if (!acceptedFiles[0]) {
return null;
}
var fr = new FileReader();
fr.onload = function () {
props.setImage(fr.result);
};
fr.readAsDataURL(acceptedFiles[0]);
})
}
multiple={false}
accept={{ "image/jpeg": [".png", ".jpg"] }}
>
{({ getRootProps, getInputProps }) => (
<section>
<div
{...getRootProps()}
style={props.image ? { padding: "0 !important" } : {}}
>
<input {...getInputProps()} />
{props.image ? (
<img
className="drop__image"
src={props.image}
alt="Your Keychain"
/>
) : (
<h3 className="drop__text">
Drag your image here, or click to select a file
</h3>
)}
</div>
</section>
)}
</Dropzone>
{isGift === true && (
<textarea
className="messageInput largeInput"
maxLength={100}
placeholder="Enter your message to your special someone here"
value={message}
onChange={(e) => setMessage(e.target.value)}
></textarea>
)}
<div className="step1Buttons">
<button
className="step1Button"
onClick={() => {
setIsGift(null);
props.setImage(null);
}}
>
Go back
</button>
{handleShowButton() && (
<>
<button className="step1Button" onClick={newKeychain}>
Create Another Keychain
</button>
<button
className="step1Button"
onClick={() => {
newKeychain();
props.setStep((step) => step + 1);
}}
>
Next
</button>
</>
)}
</div>
</>
)}
</div>
);
}
function Step2(props) {
function completed() {
return (
props.customerName !== "" &&
props.customerNumber > 0 &&
props.customerAddress !== ""
);
}
return (
<div className="step2 step center">
<div className="question center">
<h3>Let us know who will we deliver it to</h3>
<input
placeholder="Enter your name"
value={props.customerName}
onChange={(e) => props.setCustomerName(e.target.value)}
></input>
</div>
<div className="question center">
<h3>For us to give you infomations about the delivery and package</h3>
<input
type="number"
placeholder="Enter your phone number"
value={props.customerNumber}
onChange={(e) => props.setCustomerNumber(e.target.value)}
></input>
</div>
<div className="question center">
<h3>Let us know where to deliver</h3>
<textarea
className="largeInput locationInput"
placeholder="Enter your location"
value={props.customerAddress}
onChange={(e) => props.setCustomerAddress(e.target.value)}
></textarea>
</div>
<div className="step1Buttons">
<button
className="step1Button createAnother"
onClick={() => props.setStep((step) => step - 1)}
>
Go Back
</button>
<button
className="step1Button"
style={
completed()
? { backgroundColor: "#5c90a0", cursor: "pointer" }
: { backgroundColor: "#b5b5b5", cursor: "default" }
}
onClick={() => {
if (!completed()) {
return;
}
props.setStep((step) => step + 1);
}}
>
Next
</button>
</div>
</div>
);
}
function Step3(props) {
function getPrice() {
var p = 0;
props.orders.forEach((o) => {
if (o.message === "") {
p += 69;
} else {
p += 99;
}
});
return p;
}
function getDescription() {
var giftCount = 0;
var standardCount = 0;
props.orders.forEach((o) => {
if (o.message === "") {
standardCount += 1;
} else {
giftCount += 1;
}
});
return `${giftCount > 0 ? `${giftCount} Gift Keychain/s` : ""}${
giftCount * standardCount !== 0 ? " and " : ""
}${standardCount > 0 ? `${standardCount} Standard Keychain/s` : ""}`;
}
async function completeOrder(method) {
// get the order informations
// add it to the orders collection in firebase
const orderId = uuidv4();
await setDoc(doc(db, "orders", orderId), {
customerName: props.customerName,
customerNumber: props.customerNumber,
customerAddress: props.customerAddress,
timestamp: serverTimestamp(),
paymentMethod: method,
description: getDescription(),
price: getPrice(),
status: "toApprove",
});
for (let i = 0; i < props.orders.length; i++) {
let order = props.orders[i];
const fileRef = ref(storage, `orders/${orderId}`);
await uploadString(fileRef, order.image, "data_url").then(
async (snapshot) => {
const downloadUrl = await getDownloadURL(fileRef);
updateDoc(doc(db, "orders", orderId), {
orders: arrayUnion({
keychainImage: downloadUrl,
keychainMessage: order.message,
}),
});
}
);
}
props.setHasOrdered(true);
props.setOrders([]);
props.setCustomerName("");
props.setCustomerAddress("");
props.setCustomerNumber("");
props.setStep(1);
}
return (
<div className="step3 step">
<button
className="paymentMethod cod"
onClick={() => completeOrder("Cash On Delivery")}
>
Cash on Delivery
</button>
<h2 style={{ marginTop: "1rem" }}>Or</h2>
<PaypalCheckoutButton
completeOrder={() => completeOrder("Online")}
product={{ description: getDescription(), price: getPrice() }}
/>
</div>
);
}
function LandingPage(props) {
const [orders, setOrders] = useState([]);
const [customerName, setCustomerName] = useState("");
const [customerNumber, setCustomerNumber] = useState();
const [customerAddress, setCustomerAddress] = useState("");
const [step, setStep] = useState(1);
const [navbar, setNavbar] = useState(false);
const bottomRef = useRef();
const topRef = useRef();
const [image, setImage] = useState(null);
const changeBackground = () => {
setNavbar(window.scrollY > 0);
};
useEffect(() => {
window.addEventListener("scroll", changeBackground);
}, []);
function handleStepIndicator() {
if (step === 1) {
return "Step 1. Create your keychains";
} else if (step === 2) {
return "Step 2. Delivery Informations";
} else if (step === 3) {
return "Step 3. Payment Method";
}
}
const [hasOrdered, setHasOrdered] = useState(false);
return (
<>
{hasOrdered && (
<>
<div className="overlay" onClick={() => setHasOrdered(false)} />
<div className="purchaseModal">
<img src={thanks} alt="thanks" className="thanksImage"></img>
<h2>Thank you for your purchase</h2>
<p className="purchaseInfo">
We will inform you about the package via phone number that you
gave us
</p>
</div>
</>
)}
<div className="top" ref={topRef} style={{ marginTop: "-2rem" }} />
<section className="hero">
<div
className={`hero__navbar ${navbar && "active"}`}
onClick={() => {
topRef.current?.scrollIntoView({ behavior: "smooth" });
}}
>
<h2
className="hero__nav"
onClick={() => {
topRef.current?.scrollIntoView({ behavior: "smooth" });
}}
>
KEYCH
</h2>
</div>
<div className="hero__about">
<h1 className="hero__headline">BRING YOUR KEYCHAIN IDEAS TO LIFE</h1>
<p className="hero__support">
We make handmade and customized keychains using images that you like
</p>
</div>
<button
className="hero__cta"
onClick={() => {
bottomRef.current?.scrollIntoView({ behavior: "smooth" });
}}
>
<h3>Create Now</h3>
</button>
</section>
<section className="creation">
<h1 className="creation__stepIndicator">{handleStepIndicator()}</h1>
{step === 1 && (
<Step1
image={image}
setImage={setImage}
orders={orders}
setOrders={setOrders}
setStep={setStep}
/>
)}
{step === 2 && (
<Step2
customerName={customerName}
setCustomerName={setCustomerName}
customerNumber={customerNumber}
setCustomerNumber={setCustomerNumber}
customerAddress={customerAddress}
setCustomerAddress={setCustomerAddress}
setStep={setStep}
/>
)}
{step === 3 && (
<Step3
orders={orders}
setOrders={setOrders}
customerName={customerName}
customerAddress={customerAddress}
customerNumber={customerNumber}
setCustomerName={setCustomerName}
setCustomerAddress={setCustomerAddress}
setCustomerNumber={setCustomerNumber}
setHasOrdered={setHasOrdered}
setStep={setStep}
/>
)}
</section>
<div className="bottom" ref={bottomRef} />
</>
);
}
function OrderInfo(props) {
return (
<div className="orderInfo">
<div className="info__segment" style={{ marginBottom: "3rem" }}>
<h1>{props.id}</h1>
<h5>Order ID</h5>
</div>
{props.orders.map((o, i) => (
<div className="keychainInfo">
<h1>Keychain No. {i + 1}</h1>
<div className="info__segment">
<img
className="keychainImage"
src={o.keychainImage}
alt="keychainImage"
/>
<h5>Keychain Image</h5>
</div>
{o.keychainMessage && (
<div className="info__segment">
<h3 className="keychainMessage">{o.keychainMessage}</h3>
<h5>Keychain Message</h5>
</div>
)}
</div>
))}
<div className="customerInfo">
<div className="info__segment">
<h3 className="customerName">{props.customerName}</h3>
<h5>Customer Name</h5>
</div>
<div className="info__segment">
<h3 className="customerNumber">{props.customerNumber}</h3>
<h5>Customer Number</h5>
</div>
<div className="info__segment">
<h3 className="customerAddress">{props.customerAddress}</h3>
<h5>Customer Address</h5>
</div>
<div className="info__segment">
<h3 className="customerAddress">{props.paymentMethod}</h3>
<h5>Payment Method</h5>
</div>
<div className="info__segment">
<h3 className="totalPrice">₱ {props.price}</h3>
<h5>Total Price</h5>
</div>
</div>
</div>
);
}
function OrderManagement() {
const [orders, setOrders] = useState([]);
useEffect(
() =>
onSnapshot(
query(collection(db, "orders"), orderBy("timestamp", "desc")),
(snapshot) => {
setOrders(snapshot.docs);
}
),
[]
);
return (
<section className="orders">
<section className="toApprove orders__section">
<h1 className="segmentTitle">To Approve</h1>
{orders
.filter((o) => o.data().status === "toApprove")
.map((o) => (
<div className="toApproveOrder Order">
<OrderInfo
key={o.id}
orders={o.data().orders}
customerName={o.data().customerName}
customerAddress={o.data().customerAddress}
customerNumber={o.data().customerNumber}
price={o.data().price}
id={o.id}
paymentMethod={o.data().paymentMethod}
/>
<div className="toApproveControls controls">
<button
className="declineButton controlButton decline"
onClick={() => {
deleteDoc(doc(db, "orders", o.id));
}}
>
Decline
</button>
<button
className="approveButton controlButton"
onClick={() => {
updateDoc(doc(db, "orders", o.id), {
status: "toCreate",
});
}}
>
Approve
</button>
</div>
</div>
))}
</section>
<section className="toCreate orders__section">
<h1 className="segmentTitle">To Create</h1>
{orders
.filter((o) => o.data().status === "toCreate")
.map((o) => (
<div className="Order">
<OrderInfo
key={o.id}
orders={o.data().orders}
customerName={o.data().customerName}
customerAddress={o.data().customerAddress}
customerNumber={o.data().customerNumber}
price={o.data().price}
id={o.id}
paymentMethod={o.data().paymentMethod}
/>
<div className="controls">
<button
className="controlButton"
onClick={() => {
updateDoc(doc(db, "orders", o.id), {
status: "toShip",
});
}}
>
Ship Order
</button>
</div>
</div>
))}
</section>
<section className="toShip orders__section">
<h1 className="segmentTitle">To Ship</h1>
{orders
.filter((o) => o.data().status === "toShip")
.map((o) => (
<div className="Order">
<OrderInfo
key={o.id}
orders={o.data().orders}
customerName={o.data().customerName}
customerAddress={o.data().customerAddress}
customerNumber={o.data().customerNumber}
price={o.data().price}
id={o.id}
paymentMethod={o.data().paymentMethod}
/>
<div className="controls">
<button
className="controlButton"
onClick={() => {
deleteDoc(doc(db, "orders", o.id));
}}
>
Complete Order
</button>
</div>
</div>
))}
</section>
</section>
);
}
function Admin() {
const securityPassword = "Pogi Ni Vlad";
const [password, setPassword] = useState("");
return password === securityPassword ? (
<OrderManagement />
) : (
<section className="login">
<h1 className="title">Keych Admin Login</h1>
<div className="login__form">
<input
type="text"
className="form__pasword"
placeholder="Input password to enter: "
value={password}
onChange={(e) => setPassword(e.target.value)}
></input>
</div>
</section>
);
}
function App() {
return (
<PayPalScriptProvider
options={{
"client-id": process.env.REACT_APP_PAYPAL_CLIENT_ID,
currency: "PHP",
}}
>
<Router>
<div className="app">
<Routes>
<Route path="/" element={<LandingPage />}></Route>
<Route path="/admin" element={<Admin />}></Route>
</Routes>
</div>
</Router>
</PayPalScriptProvider>
);
}
export default App;
Where is the PayPalButtons component in the first code sample?
Consider using the full sample the package provides as a base. There's a currency variable set in two locations (line 10 and later within the PayPalScriptProvider) for whatever reason.

Removing Duplicates in Axios React JS

This is my code to display all the bond actors and directors, but when displaying, it has multiple of the same names, and I want to remove the duplicates.
Prettier 2.7.1
Playground link
--parser babel
Input:
import React, { useState } from "react";
import styled from "styled-components";
import axios from "axios";
const Button = styled.button`
background-color: black;
color: white;
font-size: 20px;
padding: 10px 60px;
border-radius: 5px;
margin: 10px 0px;
cursor: pointer;
`;
function ButtonClick() {
const [users, setUsers] = useState();
const fetchData = (type) => {
axios.get("https://iznfqs92n3.execute-api.us-west-1.amazonaws.com/dev/api/v2/movies")
.then((response) => {
setUsers({ [type]: Array.from(new Set(response.data))});
});
};
return (
<div>
<div>
<h2>Bond Database</h2>
<h5>Click on the buttons to see the list of all the bond movie's directors, bond actors, release year, and title songs</h5>
<Button onClick={() => fetchData("bond_actor")}>Bond Actors</Button>
{users && (
<ul>
{users?.bond_actor?.map((user) => (
<li key={user.id}>{user.bond_actor}</li>
))}
</ul>
)}
</div>
<div>
<Button onClick={() => fetchData("directors")}>Directors</Button>
{users && (
<ul>
{users?.directors?.map((user) => (
<li key={user.id}>{user.director}</li>
))}
</ul>
)}
</div>
<div>
<Button onClick={() => fetchData("title_song")}>Songs</Button>
{users && (
<ul>
{users?.title_song?.map((user) => (
<li key={user.id}>{user.title_song}</li>
))}
</ul>
)}
</div>
<div>
<Button onClick={() => fetchData("movie_year")}>Movie Year</Button>
{users && (
<ul>
{users?.movie_year?.map((user) => (
<li key={user.id}>{user.movie_year}</li>
))}
</ul>
)}
</div>
</div>
);
}
export default ButtonClick;
I tried an Array, and a Set in fetchData, but I'm having trouble implementing it. I'm just not sure if I'm putting the proper code in the right place. I would appreciate it if I get some assistance on this. Thank you!
you need to map you required data and filter out unique values from objects. I have update code it should work for you.
import React, { useState } from "react";
import styled from "styled-components";
import axios from "axios";
const Button = styled.button`
background-color: black;
color: white;
font-size: 20px;
padding: 10px 60px;
border-radius: 5px;
margin: 10px 0px;
cursor: pointer;
`;
function ButtonClick() {
const [users, setUsers] = useState();
const fetchData = (type) => {
axios
.get(
"https://iznfqs92n3.execute-api.us-west-1.amazonaws.com/dev/api/v2/movies"
)
.then((response) => {
const mappedData = (response.data || [])
.map((item) => item[type] || (type === "directors" && item.director))
.filter((newItem) => newItem);
setUsers({ [type]: Array.from([...new Set(mappedData)]) });
});
};
return (
<div>
<div>
<h2>Bond Database</h2>
<h5>
Click on the buttons to see the list of all the bond movie's
directors, bond actors, release year, and title songs
</h5>
<Button onClick={() => fetchData("bond_actor")}>Bond Actors</Button>
{users && (
<ul>
{users?.bond_actor?.map((user, index) => (
<li key={index}>{user}</li>
))}
</ul>
)}
</div>
<div>
<Button onClick={() => fetchData("directors")}>Directors</Button>
{users && (
<ul>
{users?.directors?.map((director) => (
<li key={director}>{director}</li>
))}
</ul>
)}
</div>
<div>
<Button onClick={() => fetchData("title_song")}>Songs</Button>
{users && (
<ul>
{users?.title_song?.map((title_song) => (
<li key={title_song}>{title_song}</li>
))}
</ul>
)}
</div>
<div>
<Button onClick={() => fetchData("movie_year")}>Movie Year</Button>
{users && (
<ul>
{users?.movie_year?.map((movie_year) => (
<li key={movie_year}>{movie_year}</li>
))}
</ul>
)}
</div>
</div>
);
}
export default ButtonClick;

Filtering Data to load a particular response on click

Currently I have a component that is loaded when I call my API. This content has a CitizenshipType field that separates the items from each other. I have 2 buttons on top which I want to use to filter my data. 1 button is called Europe which should bring out all the content where CitizenshipType=Europe, etc. Currently I have all my data showing without any filtering. Here is my code:
Citizenship Page:
export default function Citizenship({ items, citi }) {
return (
<>
<div>
<div onClick=//SomeFunction>
CARRIBEAN
</div>
<div onClick=//SomeFunction>
EUROPE
</div>
</div>
<div>
<div onClick=//SomeFunction>
OTHER PROGRAMS
</div>
</div>
<div>
{items &&
items.map((item) => (
<div style={{ padding: "40px" }}>
<div class="citizen-item" key={item.id}>
<div className="container6">
<img
src={`http://localhost:1337${item.Thumbnail.url}`}
/>
<div>
{item.Title}
</div>
<div>
Access to {item.CountriesAccessible} countries
</div>
<div>
<button class="findButton">FIND OUT MORE</button>
</div>
</div>
</div>
</div>
))}
{citi &&
citi.map((test) => (
<div style={{ padding: "40px" }}>
<div class="citizen-item" key={test.id}>
<div className="container6">
<img
src={`http://localhost:1337${test.Thumbnail.url}`}
/>
<div>
{test.Title}
</div>
<div>
Access to {test.CountriesAccessible} countries
</div>
<div>
<button class="findButton">FIND OUT MORE</button>
</div>
</div>
</div>
</div>
))}
</>
);
}
Home Page where I am calling the APIs:
export default function Home({ items, citi }) {
return (
<div>
<Benefits />
<Citizenship items={items} citi={citi} />
<Video />
</div>
);
}
export async function getStaticProps() {
const CitizenshipEUres = await fetch(
"http://localhost:1337/citizenships?_limit=5&CitizenshipType=Europe"
);
const CitizenshipCAres = await fetch(
"http://localhost:1337/citizenships?_limit=5&CitizenshipType=Caribbien"
);
const items = await CitizenshipEUres.json();
const citi = await CitizenshipCAres.json();
return {
props: { items, citi },
};
}
you toggle them with states:
import React, { useState } from 'react'
export const TestComponent = () => {
const [carribeanIsShowing, setShowCarribean] = useState(false)
const [europeIsShowing, setShowEurope] = useState(false)
const toggleCarribean = () => {
if (!carribeanIsShowing) {
if(europeIsShowing) {
setShowEurope(false)
}
setShowCarribean(!carribeanIsShowing)
} else {
return
}
}
const toggleEurope = () => {
if (!europeIsShowing) {
if(carribeanIsShowing) {
setShowCarribean(false)
}
setShowEurope(!europeIsShowing)
} else {
return
}
}
return (
<div>
<button onClick={() => toggleCarribean()}>
CARRIBEAN
</button>
<button onClick={() => toggleEurope()}>
EUROPE
</button>
{europeIsShowing && <div>Europe</div>}
{carribeanIsShowing && <div>carribean</div>}
</div>
)
}
Create a new variable where you store the current CitizenshipType, with a default value of 'Europe'.
const [currentCitizenshipType, setCurrentCitizenshipType] = useState(
"Europe"
);
You change your onClick event
<div onClick={() => setCurrentCitizenshipType('Europe')}>
EUROPE
</div>
And finally add a filter statment to your items.map call:
{
items
.filter((item) => item.citizenshipType === currentCitizenshipType)
.map((item)
...}

React trigger only one element in array

I am in the process of making a comment system like the one on youtube. In my implementation, when I click on modify, all comments are now inputs but only the value of the selected input will be modified. how to trigger only the element i clicked.
as you can see it triggers all the array elements
function App() {
const [open, setOpen] = useState(false);
return (
<div className="container mt-5">
<MDBRow>
{data &&
data.map((item) => (
<MDBCol md="7" lg="7" key={item.id} className="mb-4">
{!open && (
<>
<div className="font-weight-bolder float-left pr-2">
{item.name}
</div>
<div className="float-right pr-2">
<button
onClick={() => {
setOpen(true);
}}
>
Modifier
</button>
</div>
</>
)}
{open && (
<UpdateData
id={item.id}
name={item.name}
onAbort={() => setOpen(false)}
submit={() => setOpen(false)}
/>
)}
</MDBCol>
))}
</MDBRow>
</div>
);
}
export const UpdateData = ({ name, id, onAbort, submit }) => {
const formik = useFormik({
initialValues: {
id: id,
name: name,
},
onSubmit: async (values) => {
console.log(values);
submit();
},
});
return (
<form onSubmit={formik.handleSubmit}>
<MDBInput
value={formik.values.name}
name="name"
onChange={formik.handleChange}
/>
<div className="float-right">
<span onClick={onAbort} className="text-capitalize grey-text">
Cancel
</span>
<button type="submit">confirm</button>
</div>
</form>
);
};
And this is the sandbox
that i have created
To trigger only one element to be clicked you have to pass the index
function App() {
const [open, setOpen] = useState(false);
const [selectedRow, setSelectedRow] = useState(undefined);
const onSelectedRow = (index) => {
setSelectedRow(index);
setOpen(true);
}
return (
<div className="container mt-5">
<MDBRow>
{data &&
// here you will get the index
data.map((item,index) => (
<MDBCol md="7" lg="7" key={item.id} className="mb-4">
{!open && (
<>
<div className="font-weight-bolder float-left pr-2">
{item.name}
</div>
<div className="float-right pr-2">
// Now onClick pass the index of selected row to onSelectedRow
<button
onClick={() =>onSelectedRow(index)}
>
Modifier
</button>
</div>
</>
)}
// here add condition to open selected row
{ (open === true && selectedRow === index) ? (
<UpdateData
id={item.id}
name={item.name}
onAbort={() => setOpen(false)}
submit={() => setOpen(false)}
/>
) : null
}
</MDBCol>
))}
</MDBRow>
</div>
);
}
Sandbox code https://codesandbox.io/s/youthful-wave-k4eih?file=/src/App.js
If you have any queries comment below!
instead of having a false default value in your hook you should have a unique key for each element. By default, it applies to all elements.

Hide other previous div/dropdown React

I am wanting to hide other sibling divs (dropdowns in my case) when I click the statusPillDropdown
so far I click I am setting the status to true and opening the div,
{DropDown ${toggleStatusDropdown ? "open": ""}}
Do I just need to set the state to false for previously opened ones? Not sure how to do this.
thank you
import React, { useState } from "react";
import "./StatusPillDropdown.scss";
function StatusPillDropdown({
cellData,
rowItemId,
onStatusPillDropdownChange
}) {
const [toggleStatusDropdown, setToggleStatusDropdown] = useState();
const toggleDropdown = (action, rowItemId, e) => {
if (action === "pillClick") {
setToggleStatusDropdown(true);
} else {
onStatusPillDropdownChange(rowItemId, e.target.getAttribute("value"));
setToggleStatusDropdown(false);
}
};
const renderstatusPillDropdown = (cellData, rowItemId) => (
<React.Fragment>
<span
className="statusPillDropdown"
onClick={() => toggleDropdown("pillClick", rowItemId)}
>
<span className={`status-pill ${cellData.type}`}>{cellData.text}</span>
</span>
<div className="status">
<div className="dropdown-container">
<div className={`DropDown ${toggleStatusDropdown ? "open" : ""}`}>
<ul>
<li
value="Information only"
onClick={e => toggleDropdown("liClick", rowItemId, e)}
>
<span></span>Information only
</li>
<li
value="Unresolved"
onClick={e => toggleDropdown("liClick", rowItemId, e)}
>
<span className="unresolved"></span>Unresolved
</li>
<li
value="Partially Resolved"
onClick={e => toggleDropdown("liClick", rowItemId, e)}
>
<span className="partyResolved"></span>Partially Resolved
</li>
<li
value="Fully Resolved"
onClick={e => toggleDropdown("liClick", rowItemId, e)}
>
<span className="resolved"></span>Fully Resolved
</li>
</ul>
</div>
</div>
</div>
</React.Fragment>
);
return (
<React.Fragment>
{renderstatusPillDropdown(cellData, rowItemId)}
</React.Fragment>
);
}
export default StatusPillDropdown;

Categories

Resources