Answer the question
In order to leave comments, you need to log in
How to change state on click?
On the first click, the state does not change, only on the next. Tell me what's wrong?
state = {
images: [],
isLoading: false,
error: null,
query: '',
page: 1,
isModalOpen: false,
modalImage: '',
inputValue: '',
};
loadMore = () => {
this.setState(state => ({
page: state.page + 1,
}));
const { query, page } = this.state;
window.scrollTo({
top: document.documentElement.scrollHeight,
behavior: 'smooth',
});
fetchImg(query, page).then(response =>
this.setState(state => ({
images: [...state.images, ...mapper(response.data.hits)],
})),
);
};
render() {
const {
images,
error,
isModalOpen,
modalImage,
isLoading,
inputValue,
} = this.state;
return (
<section className={styles.App}>
{error && <ErrorNotification text={error.message} />}
<Searchbar
onChange={this.handleChange}
onSubmit={this.handleSubmit}
value={inputValue}
/>
{isLoading && <ImageLoader />}
{images.length > 0 && (
<ImageGallery
images={images}
onClick={this.loadMore}
onClickModal={this.openModal}
/>
)}
{isModalOpen && (
<Modal link={modalImage} closeModal={this.closeModal} />
)}
</section>
);
}
Answer the question
In order to leave comments, you need to log in
Try with callback
loadMore = () => {
this.setState(
(prevState) => ({
page: prevState.page + 1,
}),
() => {
const {query, page} = this.state;
window.scrollTo({
top: document.documentElement.scrollHeight,
behavior: 'smooth',
});
fetchImg(query, page).then((response) =>
this.setState((state) => ({
images: [...state.images, ...mapper(response.data.hits)],
}))
);
}
);
};
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question