Search code examples
reactjstypescriptreact-hooksredux-toolkitrtk-query

using 2 interdependent hooks


I need to use 2 hooks that depend on each other: useHook1() returns a list of ids and useHook2(id) is called on each of the ids and returns a name.

Basically what I want to do is:

const [allData, setData] = useState<Playerdata[]>([]);

const { data, isFetching, isError } = useHook1();

useEffect(() => {
  if (data) {
    setData(data)
  }
})

// THIS PART ***
let tempData = []
data.forEach((id) => {
  const { data: idData, isFetching, isError } = useHook2(id)
  tempData.push(idData)
})
setData(tempData)
// ***

But the *** part above gives error "Rendered more hooks than during the previous render." because I'm calling the second hook in a loop. The hooks are RTK queries: https://redux-toolkit.js.org/rtk-query/overview.


Solution

  • The code breaks the Rules of Hooks, hooks cannot be called in loops. You may need to use the lazy query version of hook #2 so you can call the trigger function within a loop and wait for its result.

    An example implementation could look similar to the following:

    const [allData, setData] = useState<Playerdata[]>([]);
    
    const { data, isFetching, isError } = useHook1Query();
    const [query2Trigger] = useHook2LazyQuery();
    
    useEffect(() => {
      const getAllData = async (data) => {
        const allData = await Promise.all(data.map(async id => {
          const { data } = await query2Trigger(id);
          return data;
        }));
        setData(allData);
      };
    
      if (data) {
        getAllData(data);
      }
    }, [data, query2Trigger]);