0

I just started studying React Hooks so I'm kind of a newbie here.

I'm struggling to find out why the below code falls into an infinite loop.

I can't find any problems with a code.

Is there anyone who could sort out this problem?

import React, { useEffect, useState } from "react";
import axios from "axios";

export interface Post {
  userId: number;
  id: number;
  title: string;
  body: string;
}

function PostFetchingOne() {
  const [id, setId] = useState(1);
  const [post, setPost] = useState<Partial<Post>>({});

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

  return (
    <>
      <div>
        <input
          type="text"
          onChange={(e) => setId(+e.target.value)}
          value={id}
        />
      </div>
      <div>{post.title}</div>
    </>
  );
}

export default PostFetchingOne;
4
  • Please remove the dependencies from useEffect. Commented Sep 30, 2021 at 12:51
  • Thanks, Krushnasinh for the feedback. removing dependencies will definitely stop an infinite loop but it also prevents state from working properly. Commented Sep 30, 2021 at 12:56
  • 1
    You should only remove post from dependencies. id is a correct dependency, post is not. If you want to console.log your post state that should be in a dedicated useEffect and that will certainly have post as a dependency: useEffect(() => { console.log('post => ', post); }, [post]); Commented Sep 30, 2021 at 12:56
  • Working perfectly. Thanks for accurate the answer Ibsn! Commented Sep 30, 2021 at 13:18

1 Answer 1

1

The second param of useEffect is an array of dependencies - when they change, useEffect will fire again. Inside your useEffect action, you perform an update to "post" on your axios get's callback.

Hence, until the axios get will fail, you'll have an infinite loop.

The solution here probably will be to remove "post" from the useEffect's dependency array.

Sign up to request clarification or add additional context in comments.

1 Comment

Great! Thanks, Ben for an accurate answer. It is working perfectly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.