I have a problem with my data after reload page, at the start it's all good and i see my component but when i refresh page it' all gone. What's wrong with my code?
export default function Heroes() {
const [heroesData, setHeroesData] = useState([]);
const heroes_fetched_data = useSelector((state) => state.heroes.heroes_data);
const dispatch = useDispatch();
useEffect(() => {
dispatch(fetchHeroes());
for (let index = 0; index < 101; index++) {
if (heroes_fetched_data) {
const item = heroes_fetched_data[0][generateRandom(0, 562)];
setHeroesData((prev) => [...prev, item]);
}
}
}, [dispatch]);
const heroes_cards = heroesData?.map((item, i) => {
return <Hero_card key={i} img={item.images.lg} name={item.name} />;
});
return (
<div className={classes.main}>
<Header />
<section className={classes.heroes}>
<ul className={classes.ully}>{heroes_cards}</ul>
</section>
<Footer />
</div>
);
}```
The problem was in incorrect put fetch func with useEffect hook. I put it in app.js like in code below and everything start working correctly:
function App() {
const isLoginModal = useSelector((state) => state.modal.isLoginModal);
const isRegisterModal = useSelector((state) => state.modal.isRegisterModal);
const dispatch = useDispatch();
useEffect(() => {
dispatch(fetchHeroes());
}, [dispatch]);
return (
<Fragment>
{isRegisterModal && <RegisterModal></RegisterModal>}
{isLoginModal && <LoginModal></LoginModal>}
<Routes>
<Route path="/" element={<Main />}></Route>
<Route path="/heroes" element={<Heroes />}></Route>
</Routes>
</Fragment>
);
}```
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.