Problem with this react flow, maximum update depth exceeded - reactjs

I have the following function
compareProducts = (empresa) => {
console.log(empresa.listaProductos)
let headerSetIn = false;
for (let i in empresa.listaProductos) {
//case1 : lookup for some data in an array, if found, setState and exit the whole function
if (pFichaInternacional && pFichaInternacional.length > 0) {
console.log("caso1")
let product: any = pFichaInternacional;
let nombreEmpresaApi = empresa.listaProductos[i].nombre
let productoFiltrado = product.filter(i => i.referencia == nombreEmpresaApi)
productoFiltrado = productoFiltrado[0]
if (productoFiltrado) {
headerSetIn = true
this.setState({
headerCardText: productoFiltrado.descripcion.toString(),
headerButtonText: productoFiltrado.label.toString(),
})
break;
}
}
}
//case 2: case1 didnt found the data, so we setup some predefined data.
if (!headerSetIn && pFichaInternacional.length > 0) {
let product: any = pFichaInternacional;
this.setState({
headerCardText: product[0].descripcion.toString(),
headerButtonText: product[0].label.toString()
})
}
}
Im receiving a
Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.
I have also tried using a setstate , instead of a local variable to set the headerSetIn parameter. But if I do it, I think js doesnt have time to evaluate the change, and both are executed, instead of only 1
Ive tried to use () , => after the first state, but it doesnt make sense in my flow

As far as I can understand is that you are calling setState in a for loop, which is not a good thing. Every time a certain condition is met setState is called, so you are constantly setting the state and rerendering smashing your performance and causing this.
I would suggest using a variable and get the needed data in the for loop then after you have excited the for loop simply use setState to set the state after all the data has been looped trough.

Related

How to properly deal with code that need to wait for previous constants to be loaded?

Here is a change to a long code before a render that wasted me time to correct many lines in the code:
Before:
const my_model:MyModel = JSON.parse(localStorage.getItem('my_model')!)
const my_positions:MyModel = JSON.parse(localStorage.getItem('my_positions')!)
After:
const waitformyIcm:Boolean = useDetailMyModelQuery(paramid.id).isSuccess;
const myIcm:undefined | MyModel| any = useDetailMyModelQuery(paramid.id).data
const waitforpositions:Boolean = usePatternPositionsPerModelQuery(paramid.icm).isSuccess;
const positions:undefined | PatternPositions[] = usePatternPositionsPerModelQuery(paramid.icm).data
The consequence is that for almost all the next constants I needed to let the program wait until those first lines completed loading. My question is how to cope with such situations because I feel my approach was not as it should:
For example this previous line would already cause crashes:
const harvestAfter:number[] = [myIcm.length_period1, myIcm.length_period2, myIcm.length_period3]
This was solved by:
const harvestAfter:number[] = waitformyIcm && [myIcm.length_period1, myIcm.length_period2, myIcm.length_period3]
Another challenge was to set a default state with data that had to be loaded first. I solved that with:
const [myFilters, setMyFilters] = useState(myfilters);
useEffect(() => setMyFilters(myfilters), [myfilters && waitforpositions]);
How to properly deal with code that need to wait for previous constants to be loaded in REACT?
Using myconst && ......?
Using useEffect?
Using useRef?
Using async await (how to do that for declaring constants)
Other?
Please don't call the same hook multiple times, that is just a waste of user memory and CPU time. (These hooks are doing work internally and you invoke them twice for no good reason.)
Just don't annotate the types here and assign them to a variable. They are already 100% typesafe from the hook.
Then, use skip:
const icmResult = useDetailMyModelQuery(paramid.id);
const patternsResult = usePatternPositionsPerModelQuery(paramid.icm, { skip: !icmResult.isSuccess });
As for the variable assignment, you could also use destructuring although I don't really see the point:
const { isSuccess: waitformyIcm, data: myIcm } = useDetailMyModelQuery(paramid.id);
As for a default state, there are many approaches. If it is an object you define inline, it would be a new reference on every render, so you best useMemo to get around that:
const filtersWithDefaults = useMemo(() => filters ?? defaultFilters, [filters])

How can I make React append a number to a variable? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I am trying to automate fetching data from a source and assigning it to a variable that goes up by 1 each loop. Each call to the data source returns a different URL (of a picture of a cat, in this case).
var i;
var urlCount = 7;
for (i=0; i < urlCount; i++) {
this.setState({...this.state, isFetching: true});
var response = await axios.get(USER_SERVICE_URL);
this.image = response.data[0];
url[i] = this.image.url;
console.log([i] + url[i]);
}
What I'm wanting it to do is create a list similar to the following:
url0 = (url here),
url1 = (another url here),
url2 = (yet another url here),
etc...
until the loop meets its condition. It works when I set the code to a manual value, like this:
url0 = this.image.url;
console.log([i] + url0);
But it doesn't work when I try to replace 0 with [i], as in the first example. It seems to be treating [i] as a property of url, instead of appending it to url. How can I make React append a number to a variable so that I can achieve the desired result above?
would not recommend to do this with a for loop, also missing information about the component itself. Also using an object here as an example, but would recommend an array.
// assuming a functional component
// add a state with a object (would rather go with an array)
const [urls, setUrls] = useState({});
// this should be within a function, better a useEffect with
// an async function defined inside and then called within the effect
var i;
var urlCount = 7;
// set fetching state
this.setState({ isFetching: true });
// loop (btw not recommended with async, better go with a map, return promises and then await Promise.all(yourArray))
for (i = 0; i < urlCount; i++) {
var response = await axios.get(USER_SERVICE_URL);
this.setState((oldState) => ({ ...oldState, [`url${i}`]: response.data[0] }));
}
// now you could access
const { url0, url1, url2... } = urls;
This is a suggestion or a tip rather than an answer
The state variable isFetching is used like a flag. You are using the setState method before fetching the data.
Calling this method will re-render the component.
Also it is called in a for loop. So the component will re-render multiple times.
My suggestion is avoid setting state unnecessarily. It will re-render the components and cause unexpected behavior.
Try this code
var i;
var urlCount = 7;
//If you set state inside a for loop and urlCount is a large value
//your component will render many times unnecessarily
this.setState({...this.state, isFetching: true});
for (i=0; i < urlCount; i++) {
var response = await axios.get(USER_SERVICE_URL);
this.image = response.data[0];
url[i] = this.image.url;
console.log([i] + url[i]);
}

Difference between componentDidUpdate and componentWillReceiveProps while creating new job

I am confused with the character of these two lifecycle methods. componentDidUpdate and componentWillReceiveProps. I am testing with two types :
existing task
new task
Check these two codes:
componentWillReceiveProps(nextProps) {
if (nextProps.jobId != this.props.jobId || (JSON.stringify(nextProps.locationData) != JSON.stringify(this.props.locationData))) {
console.log(nextProps.locationData.locations.locationDetails);
this.props.initLocationData(nextProps.locationData.locations.locationDetails);
}
}
componentDidUpdate(prevProps, prevState) {
if ((prevProps.jobId != this.props.jobId || (JSON.stringify(prevProps.locationData) != JSON.stringify(this.props.locationData)))) {
this.props.initLocationData(this.props.locationData.locations.locationDetails);
}
}
for the existing task, both methods are giving an exact correct result. For the new task, componentWillReceiveProps is giving last saved result but componentDidUpdate is giving proper result. If anyone can explain it correctly

reactjs, get array in state in for loop?

The Line console.log before if can log a number but the if statement go error with
this.state.question[i] is undefined.
after 4 hours I can't understand why?
enter image description here
You are getting an error because you are iterating your question array one too many times. If you have 5 items in the array, you want indexes 0, 1, 2, 3 and 4. Your loop tries to read index 5 as well because you have: i <= this.state.question.length. Try changing this to i < this.state.question.length instead.
Also, you are setting your state twice which is unnecessary and may trigger a re-render more than needed. Instead work with a temporary variable:
handlePlay = (e) => {
setInterval(function(){
const time = Math.round(e.target.getCurrentTime());
let obj = {currentTime: time}; //temporary variable to build your next state
for(let i = 0;i<=this.state.question.length;i++){
if(time==this.state.question[i].time){
obj.currentQuestion = i; //add stuff to it
}
}
this.setState(obj); //set your final state here
}.bind(this),1000)
}

Chrome extension won't enter for..of loop despite array length equal to 1

Background
Developing a Chrome extension (latest Chrome running on Mac OS Sierra) and I can't work out how to loop over an array which is also dynamically built at runtime.
Forgive me if I am missing something really obvious, but I cannot for the life of me work out why this for..of loop is not being entered.
I've also tried a for..in and the good old classic for loop structure i.e. for (let i = 0; i < array.length; i++) - no matter what style of loop this block is never entered, despite my array at runtime reportedly having a single item in it.
Problem Code and Statement
This code gets all files inside a directory and slices off the last 3 chars (to remove .js):
const getDirectoryContents = (path) => {
let fileNames = []
chrome.runtime.getPackageDirectoryEntry( (directoryEntry) => {
directoryEntry.getDirectory(path, {}, (subDirectoryEntry) => {
const subDirectoryReader = subDirectoryEntry.createReader()
subDirectoryReader.readEntries( (entries) => {
for (const entry of entries) {
fileNames.push(entry.name.slice(0, -3))
}
})
})
})
return fileNames
}
From inside the chrome.runtime.onStartup() callback function we want to add some context menus, which we do like so:
const addContextMenus = () => {
console.log(getDirectoryContents('commands'))
for (const command of getDirectoryContents('commands')) {
const properties = {
id: command,
title: command,
contexts: ['editable']
}
chrome.contextMenus.create(properties)
console.log(`Created context menu ${properties.title}`)
}
console.log('End addContextMenus')
}
Now, during runtime, the above code will output this inside the background page console:
However as we can see (due to the lack of the console logging "Created context menu ..." - the loop is never entered, despite the array having a length of 1.
I've found nothing online inside the Chrome developer docs that indicated that getDirectoryContents is asynchronous -- which would be one possible explanation -- but just to be sure I even tried adding a callback param to the getDirectoryContents function to ensure we are looping after the array has been populated.
EDIT: after closer inspection of the original function, it's clear that the array is in fact being returned before is has a chance to be populated by the directory reader. Answer below.
Same result!
Any help would be much appreciated. Thanks for your time.
How embarrassing! Passing in a callback function and executing it at the right time solved it. Comments were all correct - typical async issue - thanks for the support.
The problem was on line 15 of the original function: I was returning the array before it had a chance to be populated.
Working function:
const getDirectoryContents = (path, callback) => {
chrome.runtime.getPackageDirectoryEntry( (directoryEntry) => {
directoryEntry.getDirectory(path, {}, (subDirectoryEntry) => {
const subDirectoryReader = subDirectoryEntry.createReader()
let fileNames = []
subDirectoryReader.readEntries( (entries) => {
for (const entry of entries) {
fileNames.push(entry.name.slice(0, -3))
}
callback(fileNames)
})
})
})
}

Resources