I am trying to add an array to an existing array using react hooks. The only problem I have is everything I try it keeps not filling the array...
const [ residenceFinal, setResidenceFinal ] = useState([]);
I created the the value here and beneath I am trying to add an existing array to residenceFinal.
const predefinedMenuItems = {
residences: {
closeOnClick: false,
setActiveOnClick: true,
tooltip: "Residences",
content: <i className='fas fa-city'/>,
onClick: () => {
dispatch(getValue(value));
},
getContent: (controlledEntity) => {
const divTitle = "Residence info";
let res = controlledEntity.info;
const {data} = res;
let residencesInfo = [];
_.isArray(data) ? residencesInfo = data : residencesInfo.push(data);
let resiFinal = residencesInfo.map(function(el) {
var o = Object.assign({}, el);
o.isActive = false;
return o;
})
setResidenceFinal(resiFinal);
return <div className="open-data-information-drawer-item residences">
<h1>{divTitle}</h1>
<div className="open-data-item-information-container">
{residenceFinal.map((residence, idx) => {
return <div className={"open-data-item-information-container-item "+ (residence.isActive ? 'active' : '') + " item-" + idx} onClick={ (e) => onClickIdentification(residence, idx)} key={idx}>
{getOpenDataLi(residence, "identificatiecode")}
{getOpenDataLi(residence, "status")}
{getOpenDataLi(residence, "oppervlakte")}
}
</div>;
})}
</div>
</div>;
}
}
}
So I have tried alot of variations to add resiFinal to residenceFinal (naming is gonna change when i fixed it btw) but every time I check, the residenceFinal is still empty...
Can somebody help me?
Edit: added where the getContent is used.
const [ drawerContent, setDrawerContent ] = useState(<div></div>);
function handleClick(index, e) {
const selectedMenuItem = menuItems.find(m => m.id === index);
setDrawerContent(selectedMenuItem.getContent(openData));
}
<List.Item >
<div key={predefinedMenuItemId} onClick={ e => handleClick(predefinedMenuItemId, e)} className={isMenuItemActive ? 'list-item list-item-' + predefinedMenuItemId : 'list-item list-item-' + predefinedMenuItemId }></div>
</List.Item >
consoel.log()the values forresidencesInfoadnresiFinalvariables like right beforesetResidenceFinal(resiFinal)?setResidenceFinal([...resiFinal]);but correct way to set state is:setResidenceFinal([... residenceFinal, ...resiFinal]);persist the previous state as well.controlledEntity.info.datais an empty array.getContentused and when is it called? Also a getter usually is side-effect-free meaning it doesn't change the applications state when called. But that may be just due to bad naming. If your goal is to appendresiFinalto the current state then it's just:setResidenceFinal(current => [...current, ...resiFinal]);