setState array update but not removing the previous - reactjs

I have a little question. Let's assume this code
const [ChatDetailsRender, setChatDetailsRender] = useState([]);
//ChatDetailsRender it s equal= {10,20}
array=[1,2,3,4]
array.forEach((nr)=>{
setChatDetailsRender();
//here some code to add the array for each value in useState})
This is some simple example about what i wanna do and i have some difficulties because i also have some database calls. Everything looks fine but how can i update ChatDetails useState without overwriting data? like just merge these 2 arrays. Sorry, i think this questions was already here but all i can find it's examples with objects in useState, and my example contains just an simple array. Thanks.

You can concat the new value to the existing value while updating and use callback approach to set state.
const [ChatDetailsRender, setChatDetailsRender] = useState([]);
//ChatDetailsRender it s equal= {10,20}
array=[1,2,3,4]
setChatDetailsRender(previousChatDetails => previousChatDetails.concat(array));

Related

What necessitates using the value returned from useState and completely ignoring the setter function?

I stumbled onto code like this
const [activeChoice] = useState("flights");
Question Why would anyone just use the value returned from useState. The person who wrote the code is obviously never planning to update the value since he/she didn't destructure the setter function. Wouldn't it be easier to do just use a variable instead of adding the extra code "noise"? for example
const activeChoice = "flights";

How can I use a loop inside a react while appending formdata?

I guess this is a simple problem for those who are good in react. right now I have to do the frontend because we don't have any frontend dev now. I am facing an issue while passing the formdata. Here I have an array and I want to pass all the value from the array but I am able to pass just one index value.
like this
formData.append("payment", (payment[0].value));
but actually I want to pass the both the 0 and 1 index and append it in the formdata
formData.append("payment", (payment[0].value));
formData.append("payment", (payment[1].value));
I guess this is not the way because I didn't get a right output. Any help would be appreciated
const [payment, setPayment] = useState([]);
You can only pass one value to a given key,
So, if you want one key ("payment") to have a list of values, you can change your code to:
const valueList = payment.map(p => p.value);
formData.append("payment", JSON.stringify(valueList));

React updating State from Firebase Server

I have a firebase database, that has a collection called "post" and in post there 6 variables (displayName, userName, verified, text, image, avatar). The idea is, there will be multiple posts in the database.
React Code:
const [posts, setPosts] = useState([]);
//Whenever the firebase database changes, it runs this method
useEffect(() => {
db.collection("posts").onSnapshot((snapshot) =>
//Loops through all the posts and adds the data into an array
setPosts(snapshot.docs.map((doc) => doc.data()))
);
}, []);
In react, I have two state variables, posts and setPosts. I'm assuming they are initially just set to empty arrays.
Now I have the useEffect function, that I am told runs whenever the database changes/updated. First question, how does the function know that the database updated? In other words, how does the useEffect function work?
Secondly, I'm pretty sure in the end, the post variable becomes a list of all the post objects in the database. I'm not sure how that happened. I have attached the code that updates this state above, but I'm not too sure how it works. Can you please break it down and explain how it works? I'm also not sure what the setPosts state is used for.
Please let me know!
In the above
In line 1 - You have used State hooks to set up posts as an empty Array. More reading can be done here to understand what state hooks mean - https://reactjs.org/docs/hooks-state.html
Next you set up a useEffect hook function (https://reactjs.org/docs/hooks-effect.html) to make a backend (firebase) api call after rendering.
Inside the hook function you are looking up data from the posts collection in firebase and bringing back a snapshot of all the documents in that collection. db.collection("posts").onSnapshot(callBack). The callback function is called every time something changes on the underlying database using well known observer pattern (read more in following links https://rxjs-dev.firebaseapp.com/guide/overview, https://firebase.google.com/docs/reference/node/firebase.firestore.CollectionReference#onsnapshot)
Then in the onSnapshot callback function you get an array containing documents which is further mapped to an output array using the javascript Map function snapshot.docs.map((doc) => doc.data()). https://www.w3schools.com/jsref/jsref_map.asp
Finally this output array is set in the posts variable using the
setPosts() method.
Hope this breakdown helps and I suggest reading the links in detail so its clear how everything comes together.

Passing array from useState as prop

In the example here. I have to sliders and I drag them. Because I have two values I store them in useState as an array.
Then storing as an array the ComponentsWithArrayAsProp1 doesn't see changes in the state as it is the same array and does not re-render itself.
In the second example, I store values as values.toString(), but this is not a good solution.
What is a good solution for this case?
Then storing as an array the ComponentsWithArrayAsProp1 doesn't see changes in the state as it is the same array and does not re-render itself.
you are right we can solve it by creating new array everytime as follows,
function onChange1(values) {
setValues1([...values]);
}
but i think there is something wrong with react-slider .because your approach of setting array ,setValues1(values) works when we click on different points of slider1. but it deosn't work when we drag it. there is something else going wrong here ?
Option 1:
As you said, the ComponentsWithArrayAsProp1 doesn't see the changes because the array reference is the same, so it doesn't rerender. But you can save a copy of the array instead of the array itself.
function onChange1(values) {
setValues1(values.slice());
// Another way to do this
// setValues1([...values]);
}
Option 2:
You can also save the array numbers individually, like so:
const [values1Start, setValues1Start] = useState(0);
const [values1End, setValues1End] = useState(0);
function onChange1(values) {
setValues1Start(values[0]);
setValues1End(values[1]);
}
return (
<ComponentsWithArrayAsProp1 values={[values1Start, values1End]} />
);

Concatenate text from React Hook

I have following hook:
const [textToFront, setTextToFront] = useState('');
When I call setTextToFront I see that old state was cleared, I want to implement simple thing, I just want to create one big String in the hook and display. How to store and add new coming state to old state?
Try
setTextToFront(`${textToFront}${newAppendedText}`);

Resources