run useEffect an other time when my function is called

Viewed 34

I'm using useEffect to get all that I want from my backEnd,

When an onChange event is triggered, I call my function checkHandler method, where I make a post request to my backend. But the Get that I do first is not actualized, and the only way that I found to show the good stuff is to reload the page :s I think there is a better way to do it if my useEffect renders another time, but I don't know how to do it

const [message, setMessage] = useState([]);

useEffect(() => {
  axios
    .get(getAllMessage, config)
    .then((res) => {
      setMessage(res.data);
      console.log("mounted");
    })
    .catch((err) => {
      console.log(err);
    });
}, []);

const checkHandler = (e) => {
  let item = e.target.closest("[data-id]");
  const disLikeMessage = `http://localhost:3001/api/like/dislike/${item.dataset.id}`;
  const likeMessage = `http://localhost:3001/api/like/${item.dataset.id}`;

  if (!item.checked) {
    console.log("unchecked");
    axios
      .post(disLikeMessage, {}, config)
      .then((res) => {})
      .catch((err) => {
        console.log(err);
      });
  } else {
    console.log("checked");
    axios
      .post(likeMessage, {}, config)
      .then((res) => {})
      .catch((err) => {
        console.log(err);
      });
  }
};
1 Answers

You don't need to refresh useEffect as there is no concept to refresh useEffect

Create a method that will fetch your all messages

const fetchMessages = () => {
  axios
    .get(getAllMessage, config)
    .then((res) => {
      setMessage(res.data);
      console.log("mounted");
    })
    .catch((err) => {
      console.log(err);
    });
};

Inside your useEffect callback just call this fetchMessages()

useEffect(() => {
  fetchMessages();
}, []);

Here is your checkHandler()

const checkHandler = (e) => {
  let item = e.target.closest("[data-id]");
  const disLikeMessage = `http://localhost:3001/api/like/dislike/${item.dataset.id}`;
  const likeMessage = `http://localhost:3001/api/like/${item.dataset.id}`;
  fetchMessages(); // Call fetchMessages wherever you need to fetch all messages
  if (!item.checked) {
    console.log("unchecked");
    axios
      .post(disLikeMessage, {}, config)
      .then((res) => {})
      .catch((err) => {
        console.log(err);
      });
  } else {
    console.log("checked");
    axios
      .post(likeMessage, {}, config)
      .then((res) => {})
      .catch((err) => {
        console.log(err);
      });
  }
};
Related