Re-render page on clicking button even though dependency array object remains unchanged remains in Reactjs

I am using React 17.0.1. I am not able to figure out the following:

  1. Page re-renders if the button is clicked multiple times even when the id remains unchanged.
  2. Also I am encountering another error: Line 25:6: React Hook useEffect has a missing dependency: ‘id’. Either include it or remove the dependency array react-hooks/exhaustive-deps.
    I am guessing this error is caused due to the fact id is set outside of the render.
import React, { useState, useEffect } from "react";
import axios from "axios";

function DataFetcing() {
  const [post, setPost] = useState({});
  const [id, setId] = useState(1);
  const [search, setSearch] = useState(1);

  const handleClick = () => {
    console.log(post);
    setSearch(post);
  };

  useEffect(() => {
    axios
      .get(`https://jsonplaceholder.typicode.com/posts/${id}`)
      .then((res) => {
        console.log(res);
        setPost(res.data);
      })
      .catch((err) => {
        console.log(err);
        setPost(err);
      });
  }, [search]);

  return (
    <div>
      <button type="button" onClick={handleClick}>
        Fetch Post
      </button>
      <input type="text" value={id} onChange={(e) => setId(e.target.value)} />
      <span key={post.id}>{post.title}</span>
    </div>
  );
}
export default DataFetcing;

5 thoughts on “Re-render page on clicking button even though dependency array object remains unchanged remains in Reactjs”

  1. Whats up this is somewhat of off topic but I was wondering if blogs use WYSIWYG editors or if you have to manually code with HTML.

    I’m starting a blog soon but have no coding know-how so I wanted to get guidance from someone with experience.
    Any help would be greatly appreciated!

    Reply
  2. Интернет-платформа Joy casino начала деятельность на просторах отечественного интернета в две тысячи четырнадцатом году.

    Клиентам сайта предоставляется топовый программный продукт от известных производителей.
    В подборку азартных продуктов входят аппараты с
    барабанами и линиями, карточные и
    настольные игры в режиме live и
    прогнозы на спортивные события.

    Reply
  3. eu fico muito feliz quando me deparo com artigos tão bem escritos quanto o que pude
    encontrar aqui neste blog . Vou continuar visitando
    seu site pois adorei dos seus artigos .

    Reply
  4. 942537 194431An intriguing discussion will probably be worth comment. I think which you merely write a lot a lot more about this subject, it may well become a taboo subject but usually consumers are inadequate to communicate in on such topics. To another. Cheers 171882

    Reply

Leave a Comment