I have researched other cases when the state was unidentified but I am still unsuccessfully trying to subtract data from UI actions that is in the format [{},{}...]. I have managed to add to the array , using this code, which in the same time also computes the total for the item (subTotal and products are props from a child component got through a callback function):
const updateTotalPriceAndUpdatePieChartData = (subTotal,product) => {
//from here
setPieChartData([...pieChartData,{product,subTotal}])
//until up, we handle what data we need for the pieChart
setTotal(total => total + (Number.isFinite(subTotal) ? subTotal : 0))
console.log("TOTAL WAS COMPUTED")
}
And this is the state that holds the array:
const [pieChartData,setPieChartData]=React.useState([])
Yet when I try to delte an object from the state array (when an item is also deleted), I try the following :
const substractSubTotalAndSubstractTotalForPieChart = (subTotal,product,pieChartData) => {
setTotal(total - subTotal)
const lastPieChartData=pieChartData.filter(item => item !={subTotal,product})
setPieChartData(lastPieChartData)
}
It says that pieChartData is unidentified. Could you please let me know what I can do?
In substractSubTotalAndSubstractTotalForPieChart method, there is a paramter pieChartData, but there is also a state with the same name. So what happens is inside the function substractSubTotalAndSubstractTotalForPieChart's scope, the parameter pieChartData is given preference rather than the state.
Hence in your method invocation, when you don't pass this parameter, the default value of an uninitialized parameter, i.e., undefined is used.
Related
I am making a NewsCardComponent which will display slideshow of images provided in an array which will be passed down as a prop. Everytime the component is used, will have a different number of elements in images array. so i put the "imgArr" in src of img as:
<img src={imgArr[index]}>
where "index" is the state and i have to dynamically check if a component has reached to the end of array then setIndex to zero. I have achieved what I wanted but i dont know why all the techniques other than first are not working.
My useEffect:
useEffect(() => {
const interval = setInterval(() => {
indexResetter();
}, 2000);
return () => {
clearInterval(interval);
};
}, []);
Technique 1 (working fine) :
function indexResetter() {
setIndex((prev) => {
let newIndex = prev + 1;
if (newIndex > imgArr.length - 1) {
newIndex = 0;
}
return newIndex; }); }
Technique 2 (state is not setting to zero but increasing infinitely):
function indexResetter() {
let newIndex = index + 1;
if (newIndex === imgArr.length - 1) {
setIndex(0);
} else {
setIndex((prev) => prev + 1);
}
}
Technique 3 (same problem with second one):
function indexResetter() {
if (index >= imgArr.length - 1) {
setIndex(0);
} else {
setIndex((prev) => prev + 1);
}
}
In short, your useEffect() runs on initial mount, meaning that the setInterval() continues to execute the indexResetter function that was defined on the initial render, even after subsequent rerenders when new indexResetter have been created. That means the version of the indexResetter function that you end up executing only knows about the index state upon the initial mount, giving you the issue where your index doesn't change.
For more details, when you define a function, it stores a reference to the "scope" it's defined in, which includes all the variables defined in that scope:
function NewsCardComponent() {
const [index, setIndex] = useState(0);
function indexResetter() {
...
}
}
When your component above renders, it does the following:
The NewsCardComponent function gets called, creating a new "scope" (formally an environment record). This scope holds the variables and functions (bindings) such as index created within the function.
The indexResetter function gets created (note: it's just being created, it's not being called yet). This function stores an internal reference to the scope created in step 1. This is called a closure.
Later on, when indexResetter gets called, it uses the scope that it stored internally at step 2 to work out the value of the index variable.
When you update your index state using setIndex(), your component rerenders, and performs the above two steps 1 and 2 again. When this occurs, it creates a new scope for the NewsCardComponent that now holds the updated value of index, as well as creates a new indexResetter function. This means that each time you call setIndex, you effectively create new versions of the indexResster function that can see the new value of index. The value of index in the previous NewsCardComponent scope is still what it was before, and so the indexResetter function created in the previous render can still only see the old index value. The new index value is only available in the newly created scope that was created as part of the rerender.
Your problem is that your useEffect() only runs on the initial mount of your component, so the function that you're calling within your setInterval() is the first indexResetter function that was created on the initial mount. As a result, it only has visibility of the value of index for when your component initially mounted:
const interval = setInterval(() => {
indexResetter();
}, 2000);
On subsequent rerenders, the indexResetter function will be recreated, but the above setInterval() will continue to call the version of the indexResster function that was defined on the initial render (again due to a closure), which only knows about the index state at that time. As a result, the value of index within the function ends up always being the initial value.
In your working example, you're using the state setter function to access prev, which means you're no longer relying on the index value from the surrounding scope of your function. The state setter function will provide you with the most up-to-date value of your state, and so you don't face the same issue.
From what I am reading, your use effect only runs during the first render. Put index in the dependency array in your useEffect so that it runs everytime that your index changes
#robinmuhia254 is right!
The index should be passed as a dependency to the useEffect for the change to run whenever the index changes. In that case, all your techniques will result in the same output.
If you do not pass the index dependency, Techniques 2 and 3 will not meet the if-crieria(index doesn't have an updated value, it's 0 always), and the setTimeout will run the else part to increase the counter. Technique 1 works in this case because you do not bank on the index state variable at all for your computations. You compute based on the prev value.
I hope that explains!
Btw, Technique 2 has got a logical error. If you set newIndex = index + 1, the carousel will start-over before it reaches the last element.
I have made a small demo on your use case where I have also fixed the Technique 2 logic. Please have a look:
https://stackblitz.com/edit/react-1mbtpm?file=src/App.js
I am trying to build switches that create an array and have this so far:
const [playgroundFilters, setPlaygroundFilters] = useState([initialF]);
const updateItem = (whichvalue, newvalue) => {
let g = playgroundFilters[0];
g[whichvalue] = newvalue;
setPlaygroundFilters(g, ...playgroundFilters.slice());
console.log(playgroundFilters);
};
When I call up updateItem onPress it works once and every subsequent time I get an error "undefined is not an object evaluating g"
Is there an easy way to fix this?
setPlaygroundFilters expects an array so you would need to call it like that
setPlaygroundFilters([g, ...playgroundFilters.slice()]);
instead of
setPlaygroundFilters(g, ...playgroundFilters.slice());
I'm not sure you actually wants to use .slice() like that here, since it just returns the same (cloned) array.
Example Code:
(Pretend we are inside component function)
let count = useRef(0).current
useEffect(()=>{
count++
console.log(count)
}, [count])
Question:
What will happen if I run this code
(I am afraid that the endless loop execution will blow up my m1 chip macbookair, so I didn't run ^_^).
Should I awalys some_ref_object.curent = some_value to change the value?
The code probably will not do what you expect.
useRef returns a mutable object, where the object is shared across renders. But if you extract a property from that object into a variable and then reassign that variable, the object won't change.
For the same reason, reassigning the number below doesn't change the object:
const obj = { foo: 3 };
let { foo } = obj;
foo = 10;
console.log(obj);
In your code, the ref object never gets mutated. It is always the following object:
{ current: 0 }
So
let count = useRef(0).current
results in count being initially assigned to 0 at the beginning of every render.
This might be useful if for some odd reason you wanted to keep track of a number inside a given render, not to persist for any other render - but in such a case, it'd make a lot more sense to remove the ref entirely and just do
let count = 0;
Your effect hook won't do anything useful either - since count is always 0 at the start of every render, the effect callback will never run (except on the first render).
Should I awalys some_ref_object.curent = some_value to change the value
You should use current, not curent. But yes - if you want the change to persist, assign to a property of the object, instead of reassigning a standalone variable. (Reassigning a standalone variable will almost never have any side-effects.)
But, if you have something in the view that the count is used in - for example, if you want to return it in the JSX somewhere - you probably want state instead of a ref (or a let count = 0;), so that setting state results in the component re-rendering and the view updating.
I just tried it on my colleague's computer, and fortunately it didn't blow up
Conclusion 1:
The useEffect won't effect, because ref can't be denpendency.
Conclusion 2:
Only let count = useRef(0).current is the right way.
Am using function based component and am having trouble in pushing a subarray into a useState array.
my code is shown below. There is an array called mode coming from the props which i need to append it as a sub array of more
const ViewCharts = (props) =>{
//other codes
let [more,setMore] = useState([])
useEffect(()=>{
console.log(props.mode,' mode array')
let temp = [...more,props.mode]
console.log(temp, ': this will append to more')
setMore(temp)
setTimeout(()=>{
console.log(more,'after setting')
},2000)
},[//some value])
}
when the props.mode has value ['top','bottom'] i expect more to have value of [['top','bottom']] and when next time if the props.mode is ['top'] i need more to have [['top','bottom'],['top']]. but this is what am getting when i run the above code.
["top"] mode array
["top"] : this will append to more"
[] : "after setting"
why the setMore is not adding array even when the temp is having the expected value.
If I remember correctly the useState variable will change value in the next render when you set it. You are trying to read the new more value in the same render you've changed it (as you are reading it in the same effect you've set the value in), which will be [] the first time as that's how you initialised it.
Try creating a second useEffect with a more dependency to see if it gives you the value you want:
// You can also just console.log() before the return, needing no `useEffect` to see if the value indeed changed.
React.useEffect(() => {
console.log('More: ', more);
}, [more]);
https://reactjs.org/docs/hooks-state.html#recap
Line 9: When the user clicks, we call setCount with a new value. React will then re-render the Example component, passing the new count value to it.
I would suggest reading the hooks API to better understand how they work.
I have two states result which initially set to zero and val initially set to 1.
In the multiply function, I change the states as followed.
multiply(){
console.log('multiply is clicked');
console.log('numberformed is '+this.state.numberformed);
this.setState(()=>{
return{
val:this.state.val*this.state.numberformed,
result:this.state.val,
};
});
}
Here this.state.numberformed outputs 12 as I checked using console.
I want the result to be equal to 12 so I first changed val as it is seen in the code but the result still reads 1 which is the initial state of val and not the changed state of val.How should I do this?
The tricky part of setState is that the name is slightly misleading. It's actually more like scheduleStateUpdate.
The function you supply to setState returns an object that React will merge with this.state when it updates. Before the update happens, this.state always refers to the current state. Inside the return statement, the update definitely has not happened, because the update hasn't even been scheduled yet. The return statement is what schedules the update.
It looks like this might be what you were trying to do:
this.setState(() => {
const val = this.state.val * this.state.numberformed
return {
result: val
}
})
The brackets for the return statement might be tripping you up. Yes, it looks an awful lot like the brackets for a function body, or something, where statements go. But it's actually returning a javascript object from the function.
The statement
return {
result: val
}
Looks conceptually more like this:
return (
{ result: val }
)
This will add a key called result to this.state, accessible as this.state.result. In your code, assuming result was actually assigned the value you expected, two keys would have been added to state: val and result, both of which would have exactly the same value.
Since you're updating state with a simple calculation, you could make an even shorter version without using an intermediate variable like val or even a function at all:
this.setState({result: this.state.val * this.state.numberformed})
Or, more readably:
const { val, numberformed } = this.state
this.setState({result: val * numberformed})
This would set this.state.result to the result of the multiplication and leave every other key of this.state unchanged.