I'm trying to create a resuable component that will be able to take a function passed down into it, allowing it to update the state of the parent component. I've got a demo on CodeSandbox that shows the issue.
TrackListing is passed the removeTrack function from the parent, and when the delete button is clicked inside the TrackListing, the function is called with the rows index to be removed from the tracks state. Unfortunately this doesn't seem to update the tracks state.
Your not changing the state, tracks it's the same tracks.
In JS if you do -> var a = [1,23]; var b = a; console.log(a === b); it would return true. Assigning an array to another var, does not make a new array.. Doing var a = [1,23]; var b = [...a]; console.log(a === b); will do a shallow copy of a, and this as expected will return false. IOW: In react causing a state change.
Also splice(index,index), I'm pretty sure you meant splice(index, 1).
const removeTrack = (index: number) => {
const t = tracks;
t.splice(index, index);
console.log(t);
setTracks(t); //t is still the same instance of t.
};
So you will need to make a copy of t.
const removeTrack = (index: number) => {
const t = tracks;
t.splice(index, 1);
setTracks([...t]); //lets make a copy of `t` state has changed.
};
As pointed out in the comments, using the callback version of setState is a good idea, it will prevent issues of scope, here scope isn't an issue, but it's easy to get caught out by it.
Also another issue I've found with your current implementation you might want to look into, using array index as a key is not a good idea, it's not unique and you could get some funky rendering quirks, you really need unique ids for your tracks to use as the key
eg. This bit ->
tracks.map((track, index) => (
<tr key={index}> //not a good idea.
tracks.map((track, index) => (
<tr key={track.id}> //much better
Also when it comes to deleting, use the track id, using the callback/filter version in comments from Ali, you could also then just change removeTrack(track:Track) {}, and pass the track. IOW: remove index array positions from all code.
I've done a fork of your CodeSandBox with these changes to make it easier. CodeSandBox
Related
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 was doing the official ReactJs tutorial and I started to get confused about the meaning and application of immutability.
An example of the way I thought it was. Imagine i have an object in a constructor this.state = { dog: some data} and then I call a handleClick function which sets this.setState = {dog: another data}. Since I was using setState to update the value, the old reference would still be immutable, I could get to know what changed.
But in the tutorial, when they copy the "squares" state with .slice() to not change the original array and then apply the setState with a new value, I got confused.
Why they need to copy the array, couldnt they just make a reference of it in setState and change things there? The original reference would still be traceable...
EDIT:
#FelixKling Here:
class Board extends React.Component {
constructor() {
super();
this.state = {
squares: Array(9).fill(null),
};
}
handleClick(i) {
const squares = this.state.squares.slice();
squares[i] = 'X';
this.setState({squares: squares});
}
}
Couldn't they just put that inside the setState, instead of copying the initial array?
This is a really great article that helps to explain why immutability is important: http://reactkungfu.com/2015/08/pros-and-cons-of-using-immutability-with-react-js/
In fact, React.js does not need to have knowledge about what exactly changed. All it needs to know is whether the state changed at all or not.
While immutability does not provide easier answers to a what exactly changed problem, it provides a great answer to the is it changed at all or not question.
React, as the name suggests 'reacts' to changes in sate and will re-render components as the state changes. So for React, knowing if the state changes is important, unfortunately, mutating an object can make it difficult to compare.
Consider this example:
var a = 6; // numbers are primatives in javascript and compare by value
var b = 6;
var c = a; // 6
// in this case
a === b // true
b === c // true, 6
But you can't do the same for objects as they are compared by reference, that is are they pointing to the same point in memory.
var objA = { name: 'Sally' };
var objB = { name: 'Sally' };
var objC = objA;
// these are not the same object
objA.name === objB.name // true, 'Sally'
objA === objB // false, they reference different objects even though the keys and values are the same
objA === objC // true, they reference the same point in memory
The issue that arrises in React is more easily illustrated when you try and modify a value.
Let's take our number example again and make some changes:
c = 14;
a === b // true, still 6, the value of 'a' is still 6
a === c // false, 6 ≠ 14
That makes, sense we've changed the value of c, it should now be different. Let's modify our objects now.
objA.age = 30; // give objA an age property
objB.age = 35; // give objB an age property
objC.age = 40; // give objC an age property, actually changes objA
// now try equality
objA === objB // false, we already know this
objA.age === objB.age // false, as expected
objA.age === objC.age // true, possibly unexpected as it looks like we are comparing 30 to 40, but in fact our change to objC modified objA
objA === objC // true both have age set to 40
So if instead we give React a new state each time, instead of mutating it, then it's much easier to know if it should re-render.
You might be wondering then, why react doesn't just store a copy of the state and compare it to the mutated state. Maybe you're not wondering this, but it seems like this is something that React/Redux could handle and then we could just be free to mutate the state, making it easier for us.
Well it turns out that comparing two objects is quite an intensive task, first you have to make sure that they both have the same keys, and that those keys hold the same values - doesn't seem that hard - but then you realise that objects can contain many other nested objects and this comparison become recursive, checking each nested object.
It would be much easier to just pass in a new state, so that React can tell right away that it has changed.
On top of this, generating a new state also allows you to 'time travel' by keeping track of and storing previous states if you choose to.
A bit further down in the tutorial they detail the importance of immutability:
https://facebook.github.io/react/tutorial/tutorial.html#why-immutability-is-important
You can also read a lot about Immutability here: https://facebook.github.io/immutable-js/
Immutable JS is a library Facebook created for object Immutability
TLDR Links: It's basically easier to track changes and easier to determine when to re-render.
Edit regarding comment:
So you're correct that this.setState does update the object rather than mutating it.
In this example, we create a copy instead of mutating.
handleClick(i) {
const squares = this.state.squares.slice();
squares[i] = this.state.xIsNext ? 'X' : 'O';
this.setState({
squares: squares,
});
}
In this example, we mutate instead of creating a copy
handleClick(i) {
this.state.squares[i] = this.state.xIsNext ? 'X' : 'O';
this.setState({
squares: squares,
});
}
For the first example where we did not mutate, when React runs through its lifecycle events after this.setState is called and gets to shouldComponentUpdate, here's what would happen
shouldComponentUpdate(nextProps, nextState) {
// this will return true and trigger an update
return this.state.squares !== nextState;
}
For the second example, where we did mutate, here's what would happen:
shouldComponentUpdate(nextProps, nextState) {
// this will return false and will not trigger an update
return this.state.squares !== nextState;
}
and now, even though we've changed our state, since our current, mutated state is the same as our next state (set in this.setState) our react component won't update.
I'm currently reading this somewhat outdated but fine React tutorial, and I spent hours looking at this little piece of trouble, which might be more Javascript-related than React-related. At a certain point, the author starts building a small notepad app, and then there's this code:
var onChangeNote = function (id, value) {
var note = _.find(notepad.notes, function (note) {
return note.id === id;
});
if (note) {
note.content = value;
}
onChange();
};
In the app, which can be viewed in full at the forementioned article or on the respective fiddle, we have a list of notes (which by itself is an array assigned to the notes property on a notepad object defined at the top of the script), and the selected one may be changed by the user, all while using React.
What really gets me is that this is the function responsible for changing the content of the note, in the note.content = value; line, but note is a variable that got its value from _.find() (it's the lodash variant, but I already tried replacing it with the vanilla JS array.find() and nothing changed), and yet, changing it appears to be updating the actual array, I found nowhere in the code any other instance of the selected note being changed, and the onChange() function just updates the view layer (therefore it doesn't do anything to the notepad itself), so this has to be it. So is the variable note referencing the actual respective item on the notepad.notes array it got its value from even though Javascript doesn't usually do that?
Maybe I'm missing something really obvious, but I cannot put my finger on it.
Basing from the source we can check that _.find doesn't create a deep copy of the object, it returns the object from the array.
Taken from: https://github.com/lodash/lodash/blob/4.6.0-npm-packages/lodash.find/index.js
function createFind(findIndexFunc) {
return function(collection, predicate, fromIndex) {
var iterable = Object(collection);
if (!isArrayLike(collection)) {
var iteratee = baseIteratee(predicate, 3);
collection = keys(collection);
predicate = function(key) { return iteratee(iterable[key], key, iterable); };
}
var index = findIndexFunc(collection, predicate, fromIndex);
return index > -1 ? iterable[iteratee ? collection[index] : index] : undefined;
};
}
So yes, it returns the object "reference", and not a clone, so changing a property in it, changes the one in the array.
============
Here's an example regarding your question if javascript is pass by value or reference. Javascript is always pass by value except if the value passed is an object or array. Changing the value of a property to the object will also affect the original one. But changing the whole object will not affect the original one.
var arr = [{a: 1}, {a: 2}];
var x = arr.find(v => v.a === 1);
x.a = 5;
console.log(arr); // you'll see a is 5 here
x = 100; // we changed variable directly (note that x is the object that we extracted from the find function)
console.log(arr); // it's not changed, 5 is still the value
x = arr.find(v => v.a === 5); // let's get that object again
x = {a: 10}; // we replaced it with another object with same property but another value
console.log(arr); // still not changed