admin管理员组

文章数量:1317123

I am working on a React JS project that is using React query, /, React hooks and functional ponents. But it is throwing error when I use react query for API call.

This is my ponent and how I use query within it.

const App = () => {
   const [ list, updateList ] = useState([])
   const info = useQuery(["item-list"], getList, {
    retry: false,
    refetchOnWindowFocus: false,
  })

  if (info.status == "success") {
     updateList(info.data)
  }
    return (
       //view ponents here
    )
}

This is my getList API call logic

export const getList= async () => {
  const { data } = await api.get("8143487a-3f2a-43ba-b9d4-63004c4e43ea");
  return data;
}

When I run my code, I get the following error:

react-dom.development.js:14815 Uncaught Error: Too many re-renders. React limits the number of renders to prevent an infinite loop.

What is wrong with my code?

I am working on a React JS project that is using React query, https://react-query.tanstack./, React hooks and functional ponents. But it is throwing error when I use react query for API call.

This is my ponent and how I use query within it.

const App = () => {
   const [ list, updateList ] = useState([])
   const info = useQuery(["item-list"], getList, {
    retry: false,
    refetchOnWindowFocus: false,
  })

  if (info.status == "success") {
     updateList(info.data)
  }
    return (
       //view ponents here
    )
}

This is my getList API call logic

export const getList= async () => {
  const { data } = await api.get("8143487a-3f2a-43ba-b9d4-63004c4e43ea");
  return data;
}

When I run my code, I get the following error:

react-dom.development.js:14815 Uncaught Error: Too many re-renders. React limits the number of renders to prevent an infinite loop.

What is wrong with my code?

Share Improve this question edited Oct 3, 2020 at 22:18 halfer 20.3k19 gold badges109 silver badges202 bronze badges asked Sep 30, 2020 at 13:37 Wai Yan HeinWai Yan Hein 14.9k43 gold badges211 silver badges423 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 10

The main reason of that error here is you are running that code block in the if statement in an infinite loop once you have info.status === 'success' as true. Then in every render the updateList is called which triggers an another render.

Probably I would use useEffect hook here in order to listen for changes at info as:

useEffect(() => {
  if (info.status == "success") {
     updateList(info.data)
  }
}, [info])

You should remove that if statement from the body of <App /> ponent and use the useEffect hook instead as suggested above. By doing this that if statement will be checked once info is changing and not on every render.

Suggested read is Using the Effect Hook.

本文标签: