Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is useEffect not working here? Do I need to change the condition?

I am trying to run this code, but useEffect is not running a single time.

export default function DetailPage() {
  const [post, setPost] = useState({});
    const postId = useParams().postId;
    console.log(postId);

    useEffect(() => {
        console.log("useEffect called");
      const fetchPost = async () => {
        const res = await axios.get(`/posts/${postId}`);
        setPost(res.data);
        console.log(post);
        console.log("useEffect runs");
      };
      fetchPost();
      console.log("useEffect runs 2 ");
    }, [postId]);
}

Here, I am getting postId in the console, but not "useEffect run".

I have used similar code (except I am using another variable there instead of postId) in another file, and it's working there. Please help me with this code.

like image 354
evilcoder Avatar asked Oct 23 '25 03:10

evilcoder


1 Answers

Be careful, when you use setState the value of your state is changed asynchronously. So to you, it seems that the state doesn't change, but in reality, it will change. This because when you try to print the value of a state just after the setState, its value still wasn't updated. When you want to debug how a state changes with console log, create a separate hook that log every change.

Add something like this:

useEffect(()=>{
 console.log("Post state changed!")
 console.log(post);
},[post])

For what concerns the issue that your last log (console.log("useEffect runs");) is not running the only possible issues are:

  1. postId changes are not triggering useEffect (possible reason: you are using a ref inside your useParams to store values). To check it just put a console.log before running the Axios request:
const fetchPost = async () => {
   //Does this ever display your postId? If it does go to point 2.
   console.log(`Trying to fetch post ${postId}`); 
   //Furthermore if postId can be undefined I'll wrap this request with an if
   const res = await axios.get(`/posts/${postId}`);
   setPost(res.data);
   console.log("useEffect runs");
};
  1. There is an uncaught error in your network request.

First tip: always put a try-catch block when awaiting an Axios response.

This will avoid missing uncaught errors.

try {
  const res = await axios.get(`/posts/${postId}`);
  setPost(res.data);
} catch(e) {
  //Here log your error. Remember to avoid showing the log in production
}

When working with Axios I also always suggest checking the network tab of your browser to understand what is going on with your request.

I link you a post where I explain how to do it: https://stackoverflow.com/a/66232992/14106548

like image 75
Andrea Costanzo Avatar answered Oct 25 '25 18:10

Andrea Costanzo