I do have a state like this:
const [serviceListData, setserviceListData] = React.useState({});
I want to add Id
to my current state, so I implemented my code inside of useEffect
hook.
it triggers every time Insurance
and count
changes.
React.useEffect(() => {
if (selectInsurance) {
setserviceListData({
...serviceListData,
ID: filtered.ID,
});
}
}, [selectInsurance, count]);
but with this code, I only get my new state. previous state is getting removed. I console logged it and get this result:
Object { }
EachInsurance.js:56
Object { ID: 189256 }
EachInsurance.js:56
Object { ID: 189256 }
EachInsurance.js:56
Object { }
EachInsurance.js:56
Object { }
EachInsurance.js:56
Object { ID: 189257 }
so at first stage my state is a empty object. then it gets the ID
but as soon as I select another Insurace
, the state gets erased and replaced with the new one.
what is the problem with my code. I thought it would spread old value (keeping it) and then adds new ID
CodePudding user response:
When you try to add new value in serviceList, your key ID
remains same. I'm assuming that you just want to store ids in state, then object is not appropriate to use here. Instead you can use array or if you want to store unique values then use Set
.
Array
const [serviceListData, setServiceListData] = useState([]);
useEffect(() =>{
setServiceListData((prev)=> [...prev, filtered.ID]);
}, [selectInsurance, count])
SET (If unique Ids)
const [serviceListData, setServiceListData] = useState(new Set());
useEffect(() =>{
setServiceListData((prev)=> new Set(prev).add(filtered.ID));
}, [selectInsurance, count])
If you want to store data related to that particular ID, then you can use object like this:
Object
const [serviceListData, setServiceListData] = useState({});
useEffect(() =>{
setServiceListData((prev)=> Object.assign(prev, { [filtered.ID]: /*data*/ } ));
}, [selectInsurance, count])
CodePudding user response:
Hope it helps:
const [serviceListData, setServiceListData] = useState([]);
useEffect(() => {
if (selectInsurance) {
setServiceListData([...serviceListData, {ID: filtered.ID}]);
}
}, [selectInsurance, count]);