How to try the asynchronous setState synchronously?

Viewed 61

I want to know how to make asynchronous setState work synchronously. I'm making a pagination. but I want to import 5 posts each time I press the previous and next buttons. but, But it always works only when I press the button twice at first.

this is my code. <Forum.js> - component

export default function Forum() {
const [page, setPage] = useState(1);
const [list, setList] = useState([]);

const getData = async () => {
  try {
    const res = await axios.get(` ${FORUM_MOCK_API}?_page=1&_limit=5`);
    console.log(res.data[1].id);
    setList(res.data);
  } catch (error) {
    alert(error);
  }
};

const nextPost = async (e) => {
  const { name } = e.target;
  try {
    if (name === 'prevBtn' && page === 1) return;
    if (name === 'prevBtn') {
      const res = await axios.get(
        `${FORUM_MOCK_API}?_page=${page - 1}&_limit=5`,
      );
      setList(res.data);
      setPage(page - 1);
    } else if (name === 'nextBtn') {
      const res = await axios.get(`${FORUM_MOCK_API}?_page=${page}&_limit=5`);
      setList(res.data);
      setPage(page + 1);
    }
  } catch (error) {
    alert(error);
  }
};

useEffect(() => {
  getData();
  setPage(page + 1);
  setPage(page - 1);
}, []);

return (
  <ForumCon>
    <PostWrap>
      {list.map((post) => {
        return (
          <Post
            key={post.id}
            title={post.title}
            tag={post.tag.name}
            time={time}
            content={post.content}
            onClick={(e) => goToDetail(post.id)}
          />
        );
      })}
      <div className="pageBtns">
        <SmallButton
          text="prev"
          onClick={(e) => nextPost(e)}
          name="prevBtn"
        />
        <SmallButton
          text="next"
          onClick={(e) => nextPost(e)}
          name="nextBtn"
        />
      </div>
    </PostWrap>
  </ForumCon>
);

}

<SmallButton.js> -- components

export default function SmallButton({ text, onClick, name }) {
return (
  <SmallButtonCon onClick={onClick} name={name}>
    {text}
  </SmallButtonCon>
);

}

0 Answers
Related