I am trying to map the values of userIDs to listUserIds, and then use values of listUserIds as keys in listUser function. But it only show the last value. What did I go wrong?
function Search(props) { var listUserIds = [] const [userIDs, setUserIDs] = useState([]); useEffect( async() => { console.log('useEffect has been called!'); await userService.getUserAll().then(response => { var listUser = response.data; listUser.forEach(element => { setUserIDs([element.id]); }); }) .finally() }, []); Object.values(userIDs).forEach(x => listUserIds.push(x)); listUserIds.forEach(x => console.log(x)); const listUser = listUserIds.map((userId) => <div key={userId}> <ThumbnailAdmin id={userId} ></ThumbnailAdmin> </div> ) return ( <div class="col-lg-9 mt-4 mt-lg-0" style={{marginLeft:"200px"}}> <div class="row" > <div class="col-md-12"> <div class="user-dashboard-info-box table-responsive mb-0 bg-white p-4 shadow-sm"> {listUser} </div> </div> </div> </div> );
}
Advertisement
Answer
You can set the values like this. using map you can collect all the ids then you can update the state.
await userService.getUserAll().then(response => { var listUser = response.data; let ids = listUser.map(element => element.id); setUserIDs(ids); })