Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
91
rated 0 times [  94] [ 3]  / answers: 1 / hits: 12633  / 4 Years ago, fri, january 24, 2020, 12:00:00

I am using useState which has 2 array imageList and videoList and then in useEffect hook i am using forEach on data then if type is image then push to item to image .
But at last i am not getting imagelist or video list of array.



const [list, setDataType] = useState({imageList:[], videoList:[] });
useEffect (()=>{
//data is list of array
dataList.forEach(item =>{

if(!item.images) {
setDataType({...list, imageList:item})
}
else if (item.images[0].type === video/mp4)
{
setDataType({...list, videoList :item})
}
else if((item.images[0].type === images/gpeg)
{
setDataType({...list, imageList:item})
}
})
},);


Here type check is working correctly but at last i get last fetch data only which can be videolist or imageList
In last i should get list of all imageList whose type is image and same video list whose type is video


More From » reactjs

 Answers
2

It is not a proper way to call setState in a loop. Below is an attempted solution using array method filter to functionally construct the list.



const [list, setDataType] = useState({ imageList: [], videoList: [] });
useEffect(() => {
let videos = dataList.filter(item => item.images[0].type === video/mp4)
let images = dataList.filter(item => item.images[0].type === images/gpeg)
setDataType({imageList: images, videoList: videos})
}, []);



[#4952] Wednesday, January 22, 2020, 4 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
susanajamiep

Total Points: 466
Total Questions: 113
Total Answers: 108

Location: Liberia
Member since Fri, Oct 22, 2021
3 Years ago
susanajamiep questions
Sun, Jun 12, 22, 00:00, 2 Years ago
Mon, Mar 7, 22, 00:00, 2 Years ago
Wed, Jun 10, 20, 00:00, 4 Years ago
;