I have the following situation. I am fetching data from the backend and the response is a bunch of objects. I want to iterate into them and in every iteration, I want to push them into my state.
here is how I am getting data from the backend:
const allBookings = useSelector(getBookings);
useEffect(() => {
dispatch(
fetchBookings.request({
getAll: true,
})
);
}, [dispatch]);
here is my data:
bookings:{
0:{id: 294, address: '1585 Charleston Rd, Mountain View, CA, USA', broker:{name:'aaa'}},
1:{id: 294, address: '1586 Charleston Rd, Mountain View, CA, USA', broker:{name:'bbb'}},
2:{id: 294, address: '1587 Charleston Rd, Mountain View, CA, USA', broker:{name:'ccc'}}
}
Here where I am trying to set my data in an array, but something goes wrong, please help me to figure out how I can achieve. The final result should be like this:
[
{id: 294, address: '1585 Charleston Rd, Mountain View, CA, USA', broker:{name:'aaa'}},
{id: 294, address: '1586 Charleston Rd, Mountain View, CA, USA', broker:{name:'bbb'}},
{id: 294, address: '1587 Charleston Rd, Mountain View, CA, USA', broker:{name:'ccc'}}
]
if (!allBookings) return null;
const book = allBookings.bookings;
const [books, setBooks] = useState([]);
useEffect(() => {
if (book) {
const x = Object.entries(book);
setBooks(x);
}
}, [book]);
console.log('books===>', books);
allBookings
why add the same entries in local state ? You can use theallBookings
directly. Additionally you cannot use hooks conditionally, meaning that you cannot have a branch likeif (..) return null;
and then add auseXXX
hook after that line.