M
M
Mykhailo Nikolaiev2020-08-06 21:35:13
React
Mykhailo Nikolaiev, 2020-08-06 21:35:13

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

1 answer(s)
T
Timur Kostenko, 2020-08-06
@ab3

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 question

Ask a Question

731 491 924 answers to any question