Supposingly I have
0: {nick: "xaxa", pass: "215151", uid: "1123151", gallery: []}
1: {nick: "SamServer", pass: "mathlearner18", uid: "123456123456", gallery: []}
I want my item be push in the gallery that I can form it into something like this
gallery: [{img:"src",descrip:"text"},{img:"src",descrip:"text"},{img:"src",descrip:"text"},
{img:"src",descrip:"text"},{img:"src",descrip:"text"},{img:"src",descrip:"text"},]
I tried this by using push method savedAccounts.gallery.push({img:"src",descript:"text"}) but it doesn't work. Can anyone of you guys tell me how it works? I have write this in a localStorage so I can make gallery storage for each accounts that I created. I"m actually passing the props of the useState() here so you guys can get my points
I have this HeaderProfile.jsx and then the format is like this
<HeaderProfile
item={Guest}
islogin = {islogin}
changeLog = {setislogin}
savedAcc = {savedAccounts}
multisavedAcc = {setsavedAccounts}
> </HeaderProfile>
wherein const[savedAccounts,setsavedAccounts] = useState() is my localStorage.
And I am passing this in a react hook component HeaderProfile.jsx NOTE
const [savedAccounts,setsavedAccounts] =
0: {nick: "xaxa", pass: "215151", uid: "1123151", gallery: []}
1: {nick: "SamServer", pass: "mathlearner18", uid: "123456123456", gallery: []}
so I pass this in my HeaderProfile.jsx and here what it looks like
const handleUploadPost = e => {
e.preventDefault()
multisavedAcc.gallery.push({img:gallery,description:textgallery})
console.log(multisavedAcc.gallery.push({img:gallery,description:textgallery}))
}
I want to pass it to the Headerprofile.jsx and then push it to the gallery file for each target.
If you guys don't understand please don't vote me down. I just don't know if this is the right question that I show. So please edit it for me it my question sucks.
Edit I was thinking if it because I didn't make a right index where is my target for multisavedAcc[index] ? for the accounts owner
CodePudding user response:
You need to create a new instance of the state object with updated data to rerender happens. Consider the uid to update a particular one.
Update handleUploadPost as below in HeaderProfile.jsx.
const handleUploadPost = e => {
e.preventDefault();
multisavedAcc(prevState => {
return prevState.map(item => {
if (item.uid === "1123151") {
return {
...item,
gallery: [
...item.gallery,
{ img: "new_img", description: "text" }
]
};
} else {
return item
}
});
});
};
