infinite loop in useEffect working with object
hello how can I stop loop? everything works well but its looping during the clicking,when selectedfightersqry equal to one. initially it is 0 and incrementing on click
const handleClick = (id, player) => {
getFighterInfo(id);
setSelectedPlayer(player);
setSelectedFightersQty(selectedFightersQty + 1);
setFightersData(selectedFightersData)
};
useEffect(()=>{
if(selectedFightersQty===1){
setFightersData({
...selectedFightersData,
playerOne:fighter
})
}else if(selectedFightersQty===2){
setFightersData({
...selectedFightersData,
playerTwo:fighter
})
}
},[selectedFightersQty, selectedFightersData])
do you know?
how many words do you know
See also questions close to this topic
-
how to change prettier format for react native
my code formatting prettier didn't works well for react native, i don't understand where to config it but it works well with flutter
from this code
import { View, Text } from 'react-native' import React from 'react' export default function App() { return ( <View> <Text>Apps</Text> </View> ) }
it's formatted to this
import { View, Text } from 'react-native' import React from 'react' export default function App() { return ( < View > < Text > Apps < /Text> < /View> ) }
-
react-router-dom v6 params only numbers
I want add number regex in may param in react-router-dom v6. it work fin in v5 like it:
<Route path="list/:id(\d+)" element={<MyComponent/>} />
but it not work in v6.
-
How can I fixed my problem"FirebaseError: Firebase: Error (auth/invalid-api-key)."
My environment variable is ok. No comas and name mistakes but they given me error like "FirebaseError: Firebase: Error (auth/invalid-api-key)". How can I fixed it. Please Help me...
This my .env file
REACT_APP_apiKey=AIzaSyBWobnhbdeMdNpXXXXXXXXXXXXXXXXXXXX REACT_APP_authDomain=XXXXX.firebaseapp.com REACT_APP_projectId=XXXX REACT_APP_storageBucket=XXXXX.appspot.com REACT_APP_messagingSenderId=4997390XXXXX REACT_APP_appId=1:4997390XXXXX:web:cc7bc80aa1bdb78fXXXXXX REACT_APP_measurementId=G-M1XDXXXXXX
This my firebase config file
const firebaseConfig = { apiKey: process.env.REACT_APP_apiKey, authDomain: process.env.REACT_APP_authDomain, projectId: process.env.REACT_APP_projectId, storageBucket: process.env.REACT_APP_storageBucket, messagingSenderId: process.env.REACT_APP_messagingSenderId, appId: process.env.REACT_APP_appId, measurementId: process.env.REACT_APP_measurementId, }; when I debugging firebaseConfig object console.log(firebaseConfig.apiKey); ==========> undefined console.log(firebaseConfig.authDomain); ==========> undefined console.log(firebaseConfig.projectId); ==========> undefined console.log(firebaseConfig.storageBucket); ==========> undefined console.log(firebaseConfig.measurementId); ==========> undefined console.log(firebaseConfig.appId); ==========> undefined console.log(firebaseConfig.measurementId); ==========> undefined
client side given error this "FirebaseError: Firebase: Error (auth/invalid-api-key)"
-
I ned a while loop statment that makes the calculations loop and ask again
im not too sure how you add a loop statement to this. I want it to be a while loop that makes it do that the calculations repeat after finishing. I've tried but it just keeps on giving me errors. ive tried doing While statements but just will not work im not sure how you set it up as my teacher did not explain very well
import com.godtsoft.diyjava.DIYWindow; public class Calculator extends DIYWindow { public Calculator() { // getting number one double number1 = promptForDouble("Enter a number"); //getting number2 int number2 = promptForInt("Enter an integer"); //getting what to do with operation print("What do you want to do with these numbers?\nAdd\tSubtract\tMultiply\tDivide"); String operation = input(); //declaring variable here so the same one can be used double answer = 0; switch(operation) { case "add": answer = number1 + number2; print(number1 + " + " + number2 + " = " + answer); break; case "subtract": answer = number1 - number2; print(number1 + " - " + number2 + " = " + answer); break; case "multiply": answer = number1 * number2; print(number1 + " * " + number2 + " = " + answer); break; case "divide": try { answer = number1 / number2; } catch(ArithmeticException e) { print("A number cannot be divided by 0."); } print(number1 + " / " + number2 + " = " + answer); break; } double double1 = promptForDouble("Enter a number"); double double2 = promptForDouble("Enter another number"); double double3 = promptForDouble("Enter one last number"); print("What do you want to do with these numbers?\nAdd\tSubtrack\tMultiply\tDivide"); String operation2 = input(); double answer2 = 0; switch(operation2) { case "add": answer2 = double1 + double2 + double3; print(double1 + " + " + double2 + " + " + double3 + " = " + answer2); break; case "subtract": answer2 = double1 - double2 - double3; print(double1 + " - " + double2 + " - " + double3 + " = " + answer2); break; case "multiply": answer2 = double1 * double2 * double3; print(double1 + " * " + double2 + " * " + double3 + " = " + answer2); break; case "divide": try { answer2 = double1 / double2 / double3; } catch(ArithmeticException e) { print("A number cannot be divided by 0."); } print(double1 + " / " + double2 + " / " + double3 + " = " + answer2); break; } want it to loop after the code on top } private double promptForDouble(String prompt) { double number1 = 0; print(prompt); String number = input(); try { number1 = Double.parseDouble(number); } catch(NumberFormatException e){ print("That is not a number. Please enter a number."); number1 = promptForDouble(prompt); } return number1; } private int promptForInt(String prompt) { int number2 = 0; print(prompt); String number = input(); try { number2 = Integer.parseInt(number); } catch(NumberFormatException e) { print("That is not an integer. Enter an integer."); number2 = promptForInt(prompt); } return number2; } public static void main(String[] args) { new Calculator(); } }
-
Data structure for iterating between players
I am new to programming, so I started working on a small guessing game for n players In theory they are supposed to take turns trying to guess some String, I've successfully implemented that game for 1 player, but now I am struggling with how to implement iterating over all players. My code right now looks something like this:
while (!gameIsFinished) { gameIsFinished = player1.takeTurn(); }
I guess I have to use some sort of Data structure to store all my players, but what would I choose in order to be able to iterate over them in a loop?
-
How do I shutil.move my file, post processing, in python based on filename?
My code-
import pandas as pd import datetime as dt import os import shutil path = "C:/Users/rocky/Desktop/autotranscribe/python/Matching" destination_path = ('C:/Users/rocky/Desktop/autotranscribe/python/Matching/Processed') for file in os.listdir("C:/Users/rocky/Desktop/autotranscribe/python/Matching"): if file.startswith("TVC")and "(updated headers)" not in file: dfs = pd.read_excel(file, sheet_name=None) output = dict() for ws, df in dfs.items(): if ws in ["Opt-Ins", "New Voting Members", "Temporary Members"]: continue if ws in ["Voting Members", "Removed Members"]: temp = df dt = pd.to_datetime(os.path.getctime(os.path.join(path,file)),unit="s").replace(nanosecond=0) temp['Status'] = "Active" if ws == "Voting Members" else "Cancelled" output[ws] = temp writer = pd.ExcelWriter(f'{file.replace(".xlsx","")} (updated headers).xlsx') for ws, df in output.items(): df.to_excel(writer, index=None, sheet_name=ws) writer.save() writer.close() shutil.move(path, destination_path )
I just want the file that is being processed here
if file.startswith("TVC")and "(updated headers)" not in file:
to be moved to another folder directory after all my code is processed and the output file is produced..where do i apply shutil.move? i put it outside my inner loop but the file didnt populate in my dest folder as expected. Do i need an if statement? if script runs successfully and output xls produced then move original file to destination folder? -
unable to save to array react state from response from server
Hi I'm trying to save my response.data to my array state of react but it never stores the correct array but when I do a temporary array it works.
Any help would be appreciated, thanks!
const [allstudentlist, setAllStudentlist] = useState([]); await Axios.post(currentUrl, params).then((res) => { // if res.data[0][] // if res data is there then ; if (res.data["error"]) { alert(res.data["error"]); } else { // alert("Register Successful"); // console.log(res.data[0]); console.log(res.data); // works let temp = res.data; setAllStudentlist(...temp); // works console.log(temp); // returns an empty array console.log(allstudentlist); } });
Reponse data
I tried to test as well with a fake api but it looks like there is an issue with setting Arrays at react
I tried to test with codeSandbox as well with a fake API and it does not work
import "./styles.css"; import React, { Component, useState, useEffect } from "react"; import Axios from "axios"; export default function App() { const [array2, setArray] = useState([]); function handleClick() { Axios.get("https://finalspaceapi.com/api/v0/character/?limit=2").then( function (response) { console.log(response.data); setArray(response.data); console.log(array2); } ); } return ( <div className="App"> <h1>Hello CodeSandbox</h1> <h2>Start editing to see some magic happen!</h2> <button onClick={handleClick}></button> </div> ); }
-
How does React hook handle dependency lists when passing objects to child components?
Parent component like this:
function ParentComponent(){ return ( <ChildComponent data={{ x: 1, y: 2 }} /> ) }
Child component like this:
function ChildComponent({ data }){ const [sum, set] = useState(0) useEffect(() => { set(data.x + data.y) }, [data]) return ( <div>{sum}</div> ) }
If it is like the above method, it will cause repeated rendering between subgroups, because the data is always changing. How should I deal with such a scenario?
Of course I know it's possible to cache data in the parent component by
const [data] = useState({ x: 1, y: 2 })
, but I want to know if there is a better solution, if any object parameter is required useState to cache, is this implementation too complicated?In addition, it can also be stored in the child component through
const dataRef = useRef(data)
, but if a value of data changes, it will not be recalculated.Other parameters such as functions and arrays are the same.
What's wrong with my thinking?
-
How do I call react function in js map?
I have the below code, the problem is in the part where I am calling the RemoveProduct function in the map function:
function AddOrder() { const d = new Date(); let text = d.toString(); const [addOrder] = useMutation(queries.ADD_ORDER); const [editUser] = useMutation(queries.EDIT_USER_CART); const [editProduct] = useMutation(queries.EDIT_PRODUCT); function RemoveProduct (x) { let getProd = useQuery(queries.GET_PRODUCTS_BY_ID, { fetchPolicy: "network-only", variables: { _id : x._id }, }); console.log(getProd.quantity) console.log(x.quantity) let a = getProd.quantity - x.quantity console.log(a) editProduct({ variables: { _id : x._id, quantity: a }, }); return null; } const { currentUser } = useContext(AuthContext); if (error) { return <h1> error</h1>; } else if (loading) { return <h1> loading</h1>; } else if (data && getUserOrders.data && currentUser && data.getUser.cart.length > 0) { let newCart = []; let total = 0; for (let i = 0; i < data.getUser.cart.length; i++) { total += data.getUser.cart[i].price * data.getUser.cart[i].quantity; newCart.push({ orderedQuantity: data.getUser.cart[i].quantity, _id: data.getUser.cart[i]._id, name: data.getUser.cart[i].name, image: data.getUser.cart[i].image, price: data.getUser.cart[i].price, }); } newCart.map((x) => RemoveProduct(x)) editUser({ variables: { id: currentUser.uid, cart: [], }, }); } } export default AddOrder;
I get the following error when I run this code:
Uncaught Error: Rendered more hooks than during the previous render.
How can I fix this? I tried to create a separate component for RemoveProducts and call in this function but that did not work either.
-
Can someone help me understand how async + await + useEffect work in React?
I have a React app built with the Minimal template and I'm trying to follow along with one of their tutorials, in order to create a Redux slice that feeds some data to a custom component. The data itself is collected from Firebase. Below is my code:
firebase.js - helper
export function getDocuments(col) { const colRef = collection(db, col); const q = query(colRef, where('uid', '==', auth.currentUser.uid)); getDocs(q).then((snap) => { const data = snap.docs.map((d) => ({ id: d.id, ...d.data() })); return data; }); // return [1,2,3] }
product.js - Redux slice
export function getProducts() { return async (dispatch) => { dispatch(slice.actions.startLoading()); try { const products = await getDocuments('products'); dispatch(slice.actions.getProductsSuccess(products)); } catch (error) { dispatch(slice.actions.hasError(error)); } }; }
ProductList.js - component
const dispatch = useDispatch(); const { products } = useSelector((state) => state.client); useEffect(() => { dispatch(getProducts()); }, [dispatch]); useEffect(() => { if (products.length) { // setTableData(products); } }, [products]);
If I console log
data
in the helper function (firebase.js), I get the values I expect, once the promise is resolved/fulfilled. However, if I console.logclients
in the product.js slice or later in the component, I getundefined
. I assume my problem is not being able to understand how async + await + useEffect work together in order to fix this. My assumption is that I am trying to access the value before the promise is resolved and therefore before the helper function returns it. I confirmed that by returning a simple array[1, 2, 3]
in my helper function as a test.I think I am missing something fundamental here (I am not very experienced with React and JS in general and still learning things on the go). Can someone help me understand what am I doing wrong?
Thank you!
-
UseEffect firing on initial render
I am creating a front end for an API that requires a user to input both an API key as well as a device name. The issue is that the UseEffect() fetch is firing with 'undefined' as the API key on render, so the API is throwing a 401 Error code and preventing the page from rendering so that the user can put in a key.
See below code:
Api.js
const Api = ({ device, key }) => { const [data, setData] = useState(null); useEffect(() => { fetch(`APILINK&key=${key}&id=${device}`) .then((res) => res.json()) .then(setData) }, [device, key]) if (data) return ( <> <tbody> <tr> <th>Date</th> <th>Temp</th> <th>C02</th> </tr> {data.samples.map((item) => ( <tr> <td>{item.time}</td> <td>{item.data[0]}</td> <td>{item.data[1]}</td> </tr> ))} </tbody> </> ) return <div>No Data Found</div> }
Home.js
const Home = ({ setDevice, setKey }) => { const getData = (e) => { e.preventDefault(); const newDevice = e.target.deviceID.value; const apiKey = e.target.apiKey.value; setDevice(newDevice); setKey(apiKey); } return ( <> <h1>Type in a device and provide an API key below:</h1> <form onSubmit={getData}> <input type='text' placeholder="Enter Device..." id='deviceID'></input> <input style={{display: 'block'}} type='text' placeholder="Enter API Key..." id='apiKey'></input> <button>Search</button> </form> </> ) } export default Home;
App.js
const App = () => { const [device, setDevice] = useState() const [key, setKey] = useState() return ( <> <Home setDevice={setDevice} setKey={setKey} /> <Api device={device} key={key} /> </> ) } export default App;
Any help is appreciated!!
-
How to fix loading spinner when using useEffect Hooks with dependency list?
I am facing one problem when trying to add a spinner. My problem is when I add "product" dependency in useEffect hooks then my loading spinner always spinning and data not showing. Here is my code :
const [product, setProduct] = useState([]); const [msg, setMsg] = useState(''); const [loading, setLoading] = useState(false); const navigate = useNavigate(); // show all products on the manage inventory page useEffect(() => { setLoading(true); (async () => { const data = await fetchAllProduct(); if (data) { setProduct(data); setLoading(false); } })(); }, [product]);
Bellow the return code >>
{ loading === false ? <ProductTable viewProductHandle={viewProductHandle} deleteProductHandle={deleteProductHandle} product={product}> </ProductTable> : <Spinner></Spinner> }
So how do I fix that? pls, help me...
-
Plotting Cartesian Product of two infinite sets
The problem regarding plotting of Cartesian product of two finite sets have been dealt with previously in this forum. My concern is that I have two infinite sets and I want to plot the cartesian product of that. For example :
$X = {t \in \mathbb{R} | (2cos(t) , 3sin(t))}$ and $Y = {x | 0 \leq x \leq 1}$
and I want to plot X x Y. What is the way to do it ? I am using MATLAB for the plots. But I have access to python , Scilab and R too. -
Python : unable to go out of a loop "while x is != list[]"
This is my first question on Stack. I hope the explanation is understandable, and the posts' rules respected.
Problem : I try to create a display of 12 multiplication tables, 5 by 5. The code runs well, but it never stops. It seems to be a problem in the syntax of the while loop.
What I tried :
- changing the while condition with :
while lot_tab != [0]: # Stop quand vide.
while lot_tab != [""]: # Stop quand vide.
Nothing works, I don't understand. So I'm asking for your help.
Code :
LIGNE_TMUL = "%2i x %2i = %3i " nmax = 12 tab_par_lig = 5 tab_total = range(1, nmax + 1) # Soit ici 12. lot_tab = tab_total[:tab_par_lig] # Prends un lot de 5 pour l'affichage. tab_total = tab_total[tab_par_lig:] # Les enleve du stock restant. # while tab_total != []: # Test while lot_tab != []: # Stop quand vide. for x in range(1, nmax + 1): # traîter les nombres de 1 à 12. accumul = [] # Stock 1 ligne d'une table. for y in lot_tab: # Construit les colonnes. accumul.append(LIGNE_TMUL%(y, x, x * y)) # Stock une ligne dans accumul[] print("".join(accumul)) # Affiche la ligne créée avec y print("\n") # Separation verticale entre blocs de tables. lot_tab = tab_total[:tab_par_lig] # Prends un lot de 5 pour l'affichage. tab_total = tab_total[tab_par_lig:]