PayPal Checkout not showing correct total amount in react app - reactjs

Good morning. I am trying to integrate PayPal check out in my React app. Everything works fine except that the Paypal Checkout amount is not showing the same as the total cart amount. Checkout amount is fixed at $0.01 and not changing as cart amount changes. Please what could i be doing wrong ??? This is the code
#cart.js code
import React, { useContext, useState, useEffect } from "react";
import { GlobalState } from "../../../GlobalState";
import axios from "axios";
import PayPalButton from "./PaypalButton";
function Cart() {
const state = useContext(GlobalState);
const [cart, setCart] = state.userAPI.cart;
const [token] = state.token;
const [total, setTotal] = useState(0);
useEffect(() => {
const getTotal = () => {
const total = cart.reduce((prev, item) => {
return prev + item.price * item.quantity;
}, 0);
setTotal(total);
};
getTotal();
}, [cart]);
const addToCart = async () => {
await axios.patch(
"/user/addcart",
{ cart },
{
headers: { Authorization: token },
}
);
};
const increment = (id) => {
cart.forEach((item) => {
if (item._id === id) {
item.quantity += 1;
}
});
setCart([...cart]);
addToCart();
};
const decrement = (id) => {
cart.forEach((item) => {
if (item._id === id) {
item.quantity === 1 ? (item.quantity = 1) : (item.quantity -= 1);
}
});
setCart([...cart]);
addToCart();
};
const removeProduct = (id) => {
if (window.confirm("Do you want to delete this product?")) {
cart.forEach((item, index) => {
if (item._id === id) {
cart.splice(index, 1);
}
});
setCart([...cart]);
addToCart();
}
};
const tranSuccess = async (payment) => {
console.log(payment);
};
if (cart.length === 0)
return (
<h2 style={{ textAlign: "center", fontSize: "5rem" }}>Cart Empty</h2>
);
return (
<div>
{cart.map((product) => (
<div className="detail cart" key={product._id}>
<img src={product.images.url} alt="" />
<div className="box-detail">
<h2>{product.title}</h2>
<h3>${product.price * product.quantity}</h3>
<p>{product.description}</p>
<p>{product.content}</p>
<div className="amount">
<button onClick={() => decrement(product._id)}> - </button>
<span>{product.quantity}</span>
<button onClick={() => increment(product._id)}> + </button>
</div>
<div className="delete" onClick={() => removeProduct(product._id)}>
X
</div>
</div>
</div>
))}
<div className="total">
<h3>Total: $ {total}</h3>
<PayPalButton total={total} tranSuccess={tranSuccess} />
</div>
</div>
);
}
export default Cart;
PayPal button code
import React from "react";
import { PayPalScriptProvider, PayPalButtons } from "#paypal/react-paypal-js";
export default class PayPalButton extends React.Component {
render() {
const onSuccess = (payment) => {
console.log("The payment was succeeded!", payment);
this.props.tranSuccess(payment);
};
const onCancel = (data) => {
console.log("The payment was cancelled!", data);
};
const onError = (err) => {
console.log("Error!", err);
};
let env = "sandbox"; // you can set here to 'production' for production
let total = this.props.total;
let currency = "USD";
const client = {
sandbox:
"ARhnfWu_QrcGQa-PdvaY1RVriEmqGiSkfEWf-plauZQpQN_gyxaLjH9RXOhdQw7fxxxxxxxxxxxx",
production: "YOUR-PRODUCTION-APP-ID",
};
let style = {
size: "small",
color: "blue",
shape: "rect",
label: "checkout",
tagline: false,
};
return (
<PayPalScriptProvider
options={{
"client-id": "ARhnfWu_QrcGQa-PdvaY1RVriEmqGiSkfEWf-plauZQpQN_gyxaLjH9RXOhdQw7fxxxxxxxxxxxx",
}}
>
<PayPalButtons
env={env}
client={client}
commit={true}
total={total}
currency={currency}
onError={onError}
onSuccess={onSuccess}
onCancel={onCancel}
style={style}
/>
</PayPalScriptProvider>
);
}
}

I don't see a createOrder function anywhere. You need one, and it needs to invoke actions.order.create() with a JSON object that uses your total to set the amount.
See examples in the react-paypal-js storybook.

Related

Is assigned a value but never used

My code keeps bringing torusPlugin is assigned a value but never used, LoggedInView is assigned a value but never used and I don't know where I went wrong. I have checked the code and the torusPlugin function was used, same with the loggedInView.
import { useEffect, useState } from "react";
import { Card, Form } from "react-bootstrap";
import { FaComment, FaRecycle, FaRetweet, FaThumbsUp } from "react-icons/fa";
import { Web3AuthCore } from "#web3auth/core";
import {
WALLET_ADAPTERS,
CHAIN_NAMESPACES,
SafeEventEmitterProvider,
} from "#web3auth/base";
import { OpenloginAdapter } from "#web3auth/openlogin-adapter";
import { TorusWalletConnectorPlugin } from "#web3auth/torus-wallet-connector-plugin";
import Twitter from "./twitter";
import RPC from "./evm";
import { APP_CONSTANTS } from "./constants";
import "./App.css";
import { ToastContainer, toast } from "react-toastify";
import "react-toastify/dist/ReactToastify.css";
const clientId = APP_CONSTANTS.CLIENT_ID; // get from https://dashboard.web3auth.io
function App() {
const [web3auth, setWeb3auth] = useState<Web3AuthCore | null>(null);
const [provider, setProvider] = useState<SafeEventEmitterProvider | null>(
null
);
const [tweets, setTweets] = useState<Array<any> | null>(null);
const [comment, setComment] = useState<string | "">("");
const [userName, setUserName] = useState<string | "">("");
const [profileImage, setProfileImage] = useState<string | "">("");
const [newTweetName, setNewTweetName] = useState<string | "">("");
const [newTweetDescription, setNewTweetDescription] = useState<string | "">(
""
);
const refreshTime = APP_CONSTANTS.REACT_APP_REFRESH_TIMER * 1000
const [torusPlugin, setTorusPlugin] =
useState<TorusWalletConnectorPlugin | null>(null);
useEffect(() => {
const init = async () => {
try {
const web3auth = new Web3AuthCore({
clientId,
chainConfig: {
chainNamespace: CHAIN_NAMESPACES.EIP155,
chainId: "0x13881",
rpcTarget: APP_CONSTANTS.RPC_TARGET, // This is the mainnet RPC we have added, please pass on your own endpoint while creating an app
},
});
const openloginAdapter = new OpenloginAdapter({
adapterSettings: {
clientId,
network: "testnet",
uxMode: "popup",
whiteLabel: {
name: "Twitter DApp",
logoLight: APP_CONSTANTS.APP_LOGO,
logoDark: APP_CONSTANTS.APP_LOGO,
defaultLanguage: "en",
dark: true, // whether to enable dark mode. defaultValue: false
},
loginConfig: {
// Add login configs corresponding to the providers on modal
// Twitter login
jwt: {
name: "Custom Auth Login",
verifier: APP_CONSTANTS.ADAPTER_TWITTER_CLIENT_VERIFIER, // Please create a verifier on the developer dashboard and pass the name here
typeOfLogin: "twitter", // Pass on the login provider of the verifier you've created
clientId: APP_CONSTANTS.ADAPTER_TWITTER_CLIENT_ID, // Pass on the clientId of the login provider here - Please note this differs from the Web3Auth ClientID. This is the JWT Client ID
},
// Add other login providers here
},
},
});
const torusPlugin = new TorusWalletConnectorPlugin({
torusWalletOpts: {},
walletInitOptions: {
whiteLabel: {
theme: { isDark: true, colors: { primary: "#ffffff" } },
logoDark:
"https://i.ibb.co/kDNCfC9/reshot-icon-wallet-9-H3-QMSDLFR.png",
logoLight:
"https://i.ibb.co/kDNCfC9/reshot-icon-wallet-9-H3-QMSDLFR.png",
},
useWalletConnect: true,
enableLogging: true,
},
});
await web3auth.addPlugin(torusPlugin);
setTorusPlugin(torusPlugin);
await web3auth.configureAdapter(openloginAdapter);
setWeb3auth(web3auth);
await web3auth.init();
if (web3auth.provider) {
await setProvider(web3auth.provider);
let user = await web3auth.getUserInfo();
console.log('user ', user)
if(user.name && user.name !== null && user.name !== " " && user.name !== "")
setUserName(user.name)
if(user.profileImage && user.profileImage !== null && user.profileImage !== " " && user.profileImage !== "")
setProfileImage(user.profileImage)
}
await fetchAllTweets();
//eslint-disable-next-line react-hooks/exhaustive-deps
} catch (error) {
console.error(error);
}
};
init();
}, []);
const logout = async () => {
if (!web3auth) {
console.log("web3auth not initialized yet");
return;
}
await web3auth.logout();
setProvider(null);
};
const login = async () => {
if (!web3auth) {
console.log("web3auth not initialized yet");
return;
}
const web3authProvider = await web3auth.connectTo(
WALLET_ADAPTERS.OPENLOGIN,
{
loginProvider: "jwt",
extraLoginOptions: {
domain: APP_CONSTANTS.AUTH0_DOMAIN, // Please append "https://" before your domain
verifierIdField: "sub",
},
}
);
setProvider(web3authProvider);
if(web3authProvider){
let user = await web3auth.getUserInfo();
if(user.name && user.name !== null && user.name !== " " && user.name !== "")
setUserName(user.name)
if(user.profileImage && user.profileImage !== null && user.profileImage !== " " && user.profileImage !== "")
setProfileImage(user.profileImage)
}
};
/*
const getAccounts = async () => {
if (!provider) {
console.log("provider not initialized yet");
return;
}
const rpc = new RPC(provider);
const userAccount = await rpc.getAccounts();
return userAccount;
};
*/
const refresh = (e: any) => {
e.preventDefault();
fetchAllTweets();
};
const fetchAllTweets = async () => {
console.log("fetchalltweetsrunning");
if (!provider) {
console.log("provider not initialized yet");
return;
}
const rpc = new RPC(provider);
try {
let fetchedTweets = await rpc.getAllTweets();
let tweets = [...fetchedTweets];
setTweets(tweets.reverse());
} catch (error) {
console.log("error in fetching tweets", error);
}
};
const upVote = async (tweetIndex: any) => {
if (!provider) {
console.log("provider not initialized yet");
return;
}
try {
const rpc = new RPC(provider);
await rpc.sendUpVoteTransaction(tweetIndex);
fetchAllTweets();
} catch (error) {
console.log("failed to execute upvote transaction", error);
}
};
const addNewTweet = (e: any) => {
e.preventDefault();
if (!provider) {
console.log("provider not initialized yet");
return;
}
try {
const rpc = new RPC(provider);
toast.success("Tweet added successfully", {
position: toast.POSITION.TOP_CENTER,
});
rpc.sendWriteTweetTransaction(newTweetName, newTweetDescription);
setTimeout(function () {
fetchAllTweets();
}, refreshTime);
fetchAllTweets();
} catch (error) {
toast.error("Something went wrong", {
position: toast.POSITION.TOP_LEFT,
});
console.log("failed to execute new tweet transaction", error);
}
};
const addComment = async (event: any, tweetIndex: any) => {
event.preventDefault();
if (!provider) {
console.log("provider not initialized yet");
return;
}
try {
const rpc = new RPC(provider);
toast.success("Comment added successfully - refresh after 30 sec", {
position: toast.POSITION.TOP_CENTER,
});
await rpc.sendAddCommentTransaction(tweetIndex, comment);
fetchAllTweets();
} catch (error) {
toast.error("Something went wrong", {
position: toast.POSITION.TOP_LEFT,
});
console.log("failed to execute add comment transaction", error);
}
};
// Event handlers
const handleCommentChange = async (event: any) => {
setComment(event.target.value);
};
const handleNewTweetNameChange = async (event: any) => {
setNewTweetName(event.target.value);
};
const handleNewTweetDescriptionChange = async (event: any) => {
setNewTweetDescription(event.target.value);
};
const loggedInView = (
<>
<button className="button" onClick={logout}>
Logout
</button>
<div>
<h1>New Tweet</h1>
<Card>
<Card.Body>
<Card.Title>What are you thinking? Tweet it out!</Card.Title>
<Card.Text></Card.Text>
<Form.Control
as="input"
onChange={handleNewTweetNameChange}
placeholder="Tweet Name"
/>
<br></br>
<br></br>
<Form.Control
as="textarea"
onChange={handleNewTweetDescriptionChange}
placeholder="Description"
/>
<br></br>
<FaRetweet onClick={addNewTweet} />
</Card.Body>
</Card>
</div>
<div>
<h1>
All Tweets <FaRecycle onClick={fetchAllTweets} />
</h1>
{(tweets || []).map((tweet: any, i) => (
<div key={i}>
<div>
<Card>
<Card.Body>
<Card.Title>
<FaThumbsUp onClick={(event) => upVote(i)} /> {tweet.name}
</Card.Title>
<p>Total Upvotes: {tweet.upvotes}</p>
<p>Tweeted by: {tweet.fromAddress}</p>
<Card.Text>{tweet.description}</Card.Text>
<div>
<h3>All Comments</h3>
{tweet.comments.map((comment: any, j: any) => (
<div key={j}>
Comment {j + 1}: {comment}
</div>
))}
<h3>New Comment</h3>
<span>
<Form.Control
as="input"
onChange={handleCommentChange}
placeholder="Your comment..."
/>
</span>
<span>
<FaComment onClick={(event) => addComment(event, i)} />
</span>
</div>
</Card.Body>
<a
href={
APP_CONSTANTS.OPENSEA_ASSETS_URL +
"/" +
APP_CONSTANTS.CONTRACT_ADDRESS +
"/" +
i
}
rel="opener"
>
Buy Now
</a>
</Card>
</div>
</div>
))}
</div>
<div></div>
<div id="console" style={{ whiteSpace: "pre-line" }}>
<p style={{ whiteSpace: "pre-line" }}></p>
</div>
</>
);
const unloggedInView = (
<>
<div className="login-account">
<button className="twitter-bg btn" onClick={login}>
<img src="images/twitter-white.png" alt=""></img>
Login to your Twitter account
</button>
</div>
</>
);
return (
<div className="grid">
{provider ? (
<Twitter
logoutButton={logout}
handleNewTweetDescriptionChange={handleNewTweetDescriptionChange}
handleNewTweetNameChange={handleNewTweetNameChange}
addNewTweet={addNewTweet}
fetchAllTweets={fetchAllTweets}
tweets={tweets}
upVote={upVote}
handleCommentChange={handleCommentChange}
addComment={addComment}
refresh={refresh}
username={userName}
profileimage={profileImage}
/>
) : (
unloggedInView
)}{" "}
<ToastContainer />
</div>
// <div className="grid">{provider
// ? loggedInView
// : unloggedInView}</div>
// {/* <div className="grid">{loggedInView}</div> */}
);
}
export default App;
enter image description here
this is a screenshot of my code terminal
You are actually not using torusPlugin (line 38 screenshot) anywhere. Inside your useEffect you created a new const torusPlugin and then you are calling that const instead of the [torusPlugin, ...] state you declared on line 38 of the screenshot. Try to differentiate your variables / constants names otherwise would be difficult for you to identify mistakes.

React class component button setState sorting not working as intended

import AuthorSidebar from "../SubPages/AuthorSidebar";
import ReactPaginate from 'react-paginate';
import { Card, Button } from 'react-bootstrap';
export default class Author extends React.Component {
constructor(props) {
super(props);
this.state = {
author: [],
AuthorTempState: [],
selectedPage: 0,
Postsperpage: 4,
PagesVisited: 0
}
this.handlePageClick = this.handlePageClick.bind(this);
}
async recievedData() {
const res = await fetch(`https://api.quotable.io/authors?limit=30`);
const data = await res.json();
for (const element of data.results) {
element.idfav = false;
}
data.results.sort((a, b) => (a._id > b._id) ? 1 : -1)
this.setState({
author: data.results,
AuthorTempState: data.results
});
}
componentDidMount() {
if (localStorage.getItem('authors')) {
this.setState({
author: JSON.parse(localStorage.getItem('authors')),
AuthorTempState: JSON.parse(localStorage.getItem('authors'))
})
} else {
this.recievedData();
}
}
componentDidUpdate(prevProps, prevState) {
if (this.state.author !== prevState.author) {
localStorage.setItem('authors', JSON.stringify(this.state.author))
}
}
favBttn(Auth) {
const filterData = this.state.AuthorTempState.filter(data => data._id !== Auth._id)
Auth.idfav = true;
const updateAuthor = [Auth, ...filterData];
updateAuthor.sort((a, b) => (a._id > b._id) ? 1 : -1)
this.setState({
author: updateAuthor
});
}
remfavBttn(Auth) {
const filterData = this.state.AuthorTempState.filter(data => data._id !== Auth._id)
Auth.idfav = false;
const updateAuthor = [Auth, ...filterData]
updateAuthor.sort((a, b) => (a._id > b._id) ? 1 : -1)
this.setState({
author: updateAuthor
});
}
handlePageClick = (e) => {
const SelectedPage = e.selected;
const Offset = SelectedPage * this.state.Postsperpage;
this.setState({
selectedPage: SelectedPage,
PagesVisited: Offset
}, () => {
this.recievedData();
});
};
render() {
const { author } = this.state;
const PageCount = Math.ceil(author.length / this.state.Postsperpage);
console.log(author)
let sliced = author.slice(this.state.PagesVisited, this.state.PagesVisited + this.state.Postsperpage);
return (
<div className="AppWhole">
<AuthorSidebar />
<div className="App">
<div className="author">
{sliced.map(
(Author) => (
<div key={Author._id}>
<Card style={{ margin: 20 }} border="dark" bg="light" text="grey">
<Card.Body>
<Card.Title>Name: {Author.name}
{
(Author.idfav) ? (<Button size="sm" className='right' onClick={() =>
this.remfavBttn(Author)
}>Remove Favt.</Button >) : (<Button size="sm" className='right' onClick={() =>
this.favBttn(Author)
}>Add Favt.</Button >)
}
</Card.Title>
<Card.Text>
Bio: {Author.bio}
</Card.Text>
</Card.Body>
<Card.Footer>Wiki: <a href='{Author.link}'>{Author.link}</a></Card.Footer>
</Card>
</div>
))}
<div >
<ReactPaginate
pageCount={PageCount}
onPageChange={this.handlePageClick}
previousLabel={"<<"}
nextLabel={">>"}
containerClassName={'paginationLinks'}
disabledClassName={'paginationDisabled'}
activeClassName={'paginationActive'}
/>
</div>
</div>
</div>
</div>
);
}
}
So my page is an Author page which shows different authors and their details in each card which I fetched from API and then mapped. https://i.stack.imgur.com/QitTe.png
And in each card after onclick it changes to Remove Favourite. The card which is favourited makes the idfav true in the object array of the author state and false if not favourited. And there is a 2nd page which shows all the favourite authors. Now after clicking once on a card to remove fav and then clicking another card also to remove favourite the former card gets turned to add favourite automatically.
Please help me I have been stuck on this for 2 weeks now. Thank you.
Since you need to update a single object in-place in a list, here's how you do that really simply.
const bttn = (idfav) => Auth => this.setState({
author: this.state.author.map(a =>
a._id === Auth._id
// When we find the auth to update, change its idfav
? {...a, idfav }
: a
});
const favBttn = bttn(true);
const remfavBttn = bttn(false);
Or if you prefer the undried version:
function async favBttn(Auth) {
this.setState({
author: this.state.author.map(a =>
a._id === Auth._id
// When we find the auth to update, change its idfav
? {...a, idfav: true }
: a
});
}
function async favBttn(Auth) {
this.setState({
author: this.state.author.map(a =>
a._id === Auth._id
// When we find the auth to update, change its idfav
? {...a, idfav: false }
: a
});
}

How to console.log the

I have a simple React component and inside of it I am fetching data from a remote API, and I want to console.log it in useEffect. I am trying to do it but nothing doesn't get logged into the console, why? What am I missing here? Here is the component:
import React, { useState, useEffect } from 'react';
import { useLocalization } from '#progress/kendo-react-intl';
import { Card, CardHeader, Avatar, CardTitle, CardSubtitle } from '#progress/kendo-react-layout';
import { guid } from '#progress/kendo-react-common';
import { Scheduler } from './../components/Scheduler';
import { employees } from './../resources/employees';
import { images } from './../resources/images';
import { orders, ordersModelFields } from './../resources/orders';
import { teams } from './../resources/teams';
// const orderEmployees = employees.filter(employee => employee.jobTitle === 'Sales Representative');
// const initialFilterState = { };
// orderEmployees.forEach(employee => {
// if(employee.fullName === 'Wait Peperell') {
// initialFilterState[employee.id] = false;
// } else {
// initialFilterState[employee.id] = true;
// }
// });
const Planning = () => {
const localizationService = useLocalization();
const [filterState, setFilterState] = React.useState(initialFilterState);
const [data, setData] = React.useState(orders);
const [fetchedData, setFetchedData] = React.useState(null);
useEffect(() => {
fetch("https://mocki.io/v1/29b83c0b-1a55-430d-a173-92b3632e04aa")
.then(response => response.json())
// 4. Setting *dogImage* to the image url that we received from the response above
.then(data => setFetchedData(data))
console.log(fetchedData)
},[])
// console.log(fetchedData)
const onDataChange = React.useCallback(
({ created, updated, deleted }) => {
setData(old => old
// Filter the deleted items
.filter((item) => deleted.find(current => current[ordersModelFields.id] === item[ordersModelFields.id]) === undefined)
// Find and replace the updated items
.map((item) => updated.find(current => current[ordersModelFields.id] === item[ordersModelFields.id]) || item)
// Add the newly created items and assign an `id`.
.concat(created.map((item) => Object.assign({}, item, { [ordersModelFields.id]: guid() }))))
},
[]
);
const onEmployeeClick = React.useCallback(
(employeeId) => {
setFilterState({
...filterState,
[employeeId]: !filterState[employeeId]
});
},
[filterState, setFilterState]
);
return (
<div id="Planning" className="planning-page main-content">
<div className="card-container grid">
<h3 className="card-title">{localizationService.toLanguageString('custom.teamCalendar')}</h3>
{
orderEmployees.map(employee => {
return (
<div
key={employee.id}
onClick={() => onEmployeeClick(employee.id)}
style={!filterState[employee.id] ? {opacity: .5} : {}}
>
<Card style={{ borderWidth: 0, cursor: 'pointer'}}>
<CardHeader className="k-hbox" >
<Avatar type='image' shape='circle' size={'large'} style={{
borderWidth: 2,
borderColor: teams.find(({teamID}) => teamID === employee.teamId).teamColor,
}}>
<div className="k-avatar-image" style={{
backgroundImage: images[employee.imgId + employee.gender],
backgroundSize: 'cover',
backgroundPosition: 'center center',
}}
/>
</Avatar>
<div>
<CardTitle style={{color: teams.find(({teamID}) => teamID === employee.teamId).teamColor}}>{employee.fullName}</CardTitle>
<CardSubtitle>{employee.jobTitle}</CardSubtitle>
</div>
</CardHeader>
</Card>
</div>
);
})
}
<div className="card-component" >
<Scheduler
data={data.filter(event => filterState[event.employeeID])}
onDataChange={onDataChange}
modelFields={ordersModelFields}
resources={[
{
name: 'Teams',
data: teams,
field: 'teamID',
valueField: 'teamID',
textField: 'teamName',
colorField: 'teamColor'
}
]}
/>
</div>
</div>
</div>
);
}
export default Planning;
I also tried to place the console.log outside of useEffect but still, nothing gets console.logged.
You need to look how useEffect work, setFetchedData is async.
Create another useEffect only for console.log.
useEffect(() => {
console.log(fetchedData);
},[fetchedData]); // Update at the first render + when fetchedData state change.
You can do it like this
useEffect(() => {
fetch("https://mocki.io/v1/29b83c0b-1a55-430d-a173-92b3632e04aa")
.then((response) => response.json())
// 4. Setting *dogImage* to the image url that we received from the response above
.then((data) => {
setFetchedData(data);
console.log(data);
});
}, []);
or juste create another useEffect that listens to fetchedData change, like this
useEffect(() => {
console.log(fetchedData);
}, [fetchedData]);

Radio buttons not toggling, checked or highlighted

import React, { useState, useEffect, Fragment } from "react";
import Button from "../../../Resources/Forms/Button";
import Switch from "../../../Resources/Forms/Switch";
import { POST } from "../../../Utils/api";
import Radio from "../../../Resources/Forms/Radio";
import withAppData from "../../../HOC/withAppData";
const InventorySettings = (props) => {
const [state, setState] = useState({});
const [isSaving, setIsSaving] = useState();
const [isStockRequestChecked, setIsStockRequestChecked] = useState(false);
const getStatus = id => {
return props.context.isSettingsActivated(id) ? 1 : 0;
};
const setBusinessSettings = async () => {
const defaultSettings = [
{ state: "enableStockRequest", id: 53 },
{ state: "connectWarehousePickStock", id: 52 },
{ state: "approveRequestOtp", id: 51 },
{ state: "approveRequestManually", id: 50 }
];
for (const setting of defaultSettings) {
await setState({ [setting.state]: getStatus(setting.id) });
}
};
function chooseApprovalMethod(methodType) {
const currentValue = state[methodType];
setState({[methodType]
: currentValue === 1 ? 0: 1})
}
async function saveApprovalMethod() {
setIsSaving(true)
const approvalSettings = [{text:"approvalRequestManually", id: 51}, {text:"approveRequestOtp", id: 50}]
for(const el of approvalSettings) {
const currentValue = state[el.text];
const data = {
settingId: el.id,
status: currentValue
}
await POST(`Common/AddBusinessSetting`, data);
}
setIsSaving(false);
props.context.getBusinessSettings();
}
const updateBasicSettings = async (id, key) => {
setState({ [key]: !state[key] ? 1 : 0 });
const data = {
SettingId: id,
Status: state[key],
};
await POST(`Common/AddBusinessSetting`, data);
props.context.getBusinessSettings();
};
useEffect(() => {
setBusinessSettings();
}, []);
return (
<Fragment>
<div className="basic-settings-section">
<Switch
label={"Connect Warehouse Stock to pick stock"}
light={true}
checked={state && state.connectWarehousePickStock === 1}
onChange={() => updateBasicSettings(52, "connectWarehousePickStock")}
></Switch>
</div>
<div className="basic-settings-section">
<Switch
label={"Stock Request"}
light={true}
checked={isStockRequestChecked}
onChange={() => setIsStockRequestChecked(!isStockRequestChecked)}
></Switch>
{isStockRequestChecked && (
<div className="basic-settings-plan-generate">
<div
className="form__label"
style={{ padding: "2px", marginBottom: "20px" }}
>
<p>Please choose an approval method</p>
</div>
<Radio
label={"Manual Approval"}
name="approval"
value="50"
id="50"
checked={state && state.approveRequestManually === 1}
// onChange={() => (chooseApprovalMethod)}
/>
<Radio
label={"OTP Approval"}
name="approval"
value="51"
id="51"
checked={state && state.approveRequestOtp === 1}
// onChange={() => (chooseApprovalMethod)}
/>
<div className="password-settings-btn"
// onClick={props.context.showToast}
>
<Button
type={"outline"}
size={"medium"}
text={"Save"}
disabled={!state.approveRequestOtp && !state.approveRequestManually}
withMargin={false}
loading={isSaving}
onClick={saveApprovalMethod}
></Button>
</div>
</div>
)}
</div>
</Fragment>
);
}
export default withAppData(InventorySettings);
I added the chooseApprovalMethod function to the radio buttons but still I wasn't getting it well. So I had to call there state using state.text is equal to 1. Please help me out I don't think I know what I'm doing anymore.
Please above are my code, the radio buttons aren't checking or highlighting, so I want them to be checked when clicked on, and I want there ids to be saved when clicking on the save button.
So please guys help me out, as I don't understand it anymore.

How to display a Modal, without updating state

I've spun my gears an entire work day trying to figure out how to do this. I have a component that renders a PowerBi embedded report. I have a button on the page that needs to pop open a Bootstrap Modal wrapped component. I can do this normally with state, but due to having a embedded PowerBi report, I cannot change the state (as this will re-render the PowerBI report which takes time, and also resets the report). I have tried using useRef(), to store this variable but obviously it doesn't notify the Modal component of the change.
Thoughts? Any advice?
import React, {useEffect, useRef, useState,useMemo} from 'react';
import ReportManager from '../managers/reportManager';
import SubscribeModel from '../components/subscription/SubscribeModal';
// #ts-ignore
import Report from 'powerbi-report-component';
import {FaChartLine, FaChartBar, FaDesktop, FaPrint, FaMailBulk} from 'react-icons/fa';
import PreloadManager from '../managers/preloadManager';
// #ts-ignore
import LoadingOverlay from 'react-loading-overlay';
import Preloader from '../components/Preloader';
interface ReportConfig {
id : string;
name : string;
webUrl : string;
embedUrl : string; //Embed URL
datasetId : string; //Report ID
embedToken : string; //Embed Token
}
class ReportConfigReal implements ReportConfig {
'id' : string;
'name' : string;
'webUrl' : string;
'embedUrl' : string;
'datasetId' : string;
'embedToken' : string;
'expiration' : string;
}
const Reports = (props : any) => {
const [config,
setConfig] = useState({
id: "",
name: "",
webUrl: "",
embedUrl: "",
embedToken: "",
expiration: ""
});
const [currentUser,
setCurrentUser] = useState(props.currentuser);
const [reportList,
setReportList] = useState(new Array());
const [reportId,
setReportId] = useState(props.match.params.report_id);
const [loading,
setLoading] = useState(false);
const [reportsLoading,
setReportsLoading] = useState(false);
const [report,
setReport] = useState(null);
const [subModal,
setSubModal] = useState(false);
let reportManager : ReportManager = new ReportManager();
let preloadManager : PreloadManager = new PreloadManager();
const currentPage = useRef(null);
const showSubscribe = useRef(null);
const createExpiration = (minutes : number) => {
const date = new Date();
return new Date(date.getTime() + minutes * 60000);
};
const onLoadAndSetTokenListener = (reportFromCallback : any) => {
setTokenExpirationListener(config.expiration, 1);
setReport(reportFromCallback);
};
const setTokenExpirationListener = (tokenExpiration : string, minutesToRefresh = 2) => {
// time until token refresh in milliseconds
const currentTime = Date.now();
const expiration = Date.parse(tokenExpiration);
const safetyInterval = minutesToRefresh * 60 * 1000;
let timeout = expiration - currentTime - safetyInterval;
// if token already expired, generate new token and set the access token
if (timeout <= 0) {
console.log('Updating Report Embed Token');
updateToken() // set timeout so minutesToRefresh minutes before token expires, token will be
// updated;
} else {
console.log('Report Embed Token will be updated in ' + timeout + ' milliseconds.');
setTimeout(() => {
console.log('Set time out');
updateToken();
}, timeout);
}
};
const updateToken = () => {
console.log('Update token called');
// Generate new EmbedToken (Axios call to get config/ token)
reportManager
.generateEmbedToken(currentUser)
.then((res : any) => {
// Set AccessToken (Use the report object)
if (report !== null) {
report
.setAccessToken(res.embedToken)
.then(() => {
console.log('new token set');
setTokenExpirationListener(createExpiration(2).toString(), 1);
})
.catch((err : any) => console.error('Error setting token', err));
}
});
};
const handleFullScreen = () => {
var elem = document.documentElement;
elem.requestFullscreen();
};
const handlePrint = () => {
window.print();
};
const handleSubscribe = () => {
console.log("page", currentPage.current);
console.log("showsub", showSubscribe);
};
const handleReportChange = (e : any) => {
window.location.href = '/reports/' + e;
};
const handleDataSelected = (data : any) => {
console.log("data selected", data);
};
const handlePageChange = (data : any) => {
console.log("page changed", data);
currentPage.current = data.newPage;
};
useEffect(() => {
let promiseList : any = [];
setLoading(true);
setReportsLoading(true);
if (currentUser && currentUser.allowedReports.length !== 0) {
currentUser
.allowedReports
.forEach((report : string) => {
promiseList.push(reportManager.getReportInfo(currentUser, report).then((info : any) => {
return info;
}),);
});
}
Promise
.all(promiseList)
.then(values => {
setReportList(values);
});
if (currentUser && currentUser.allowedReports.length !== 0 && currentUser.authenticated) {
if (reportId === undefined) {
reportManager
.getReport(currentUser)
.then(data => {
setConfig(data);
setLoading(false);
setReportsLoading(false);
})
.catch(error => {
console.log(error);
});
} else {
reportManager
.getReportInfo(currentUser, reportId)
.then((info : any) => {
setConfig(info);
setLoading(false);
setReportsLoading(false);
});
}
}
}, []);
return (
<LoadingOverlay active={loading} spinner={< Preloader />}>
<div>
<div
className={reportsLoading !== true
? 'slide-wrapper'
: 'col-sm-12 loading-delete'}>
<div id="slide-report">
<div className="menu_icon">
<div>
<FaChartLine color="#003267" size="30"/>
</div>
<span>Reports</span>
</div>
<div className="menu_content">
<ul>
{reportList.map((report, index) => {
return (
<li key={index} onClick={() => handleReportChange(report.id)}>
<FaChartBar className="icon-slide" color="#fff" size="30"/>
<span>{report
.name
.slice(0, 25)}</span>
</li>
);
})}
</ul>
</div>
</div>
<div id="slide-full-screen">
<div className="menu_icon" onClick={handleFullScreen}>
<div>
<FaDesktop color="#003267" size="30"/>
</div>
<span>Full Screen</span>
</div>
</div>
<div id="slide-print">
<div className="menu_icon" onClick={handlePrint}>
<div>
<FaPrint color="#003267" size="30"/>
</div>
<span>Print</span>
</div>
</div>
<div id="slide-subscribe">
<div className="menu_icon" onClick={handleSubscribe}>
<div>
<FaMailBulk color="#003267" size="30"/>
</div>
<span>Subscribe</span>
</div>
</div>
</div>
<div
key={reportId}
className={loading !== true
? 'col-sm-12'
: 'col-sm-12 loading-delete'}>
<Report
className={reportId}
embedType="report"
tokenType="Embed"
pageName={reportId}
accessToken={config.embedToken}
embedUrl={config.embedUrl}
embedId={config.id}
permissions="All"
reportMode="view"
onLoad={onLoadAndSetTokenListener}
onPageChange={handlePageChange}
onSelectData={handleDataSelected}
style={{
height: '90vh',
width: '100%',
display: 'block',
top: '0',
left: '0',
position: 'absolute',
border: '0',
padding: '20px',
background: '#fff',
zIndex: '1'
}}/>
</div>
</div>
<SubscribeModel show={false} />
</LoadingOverlay>
);
};
export default Reports;
This looks like the wrong way to go about doing it but this will open a modal without having to update state. Have you considered looking into componentShouldUpdate? The powerBiReport should also not be re-rendered unless any props that are passed into it have changed or state within the report itself has changed so consider looking there.
/* -- snip -- */
onButtonClick={() => createModal(<YourModal onClose={removeModal}/>)}
/* -- snip -- */
const createModal(component) {
const container = document.appendChild("div");
container.id = "modal-container";
ReactDOM.render(container, component);
}
const removeModal() {
const container = document.getElementById("modal-container");
ReactDOM.unmountComponentAtNode(container);
}

Resources