search

Home  >  Q&A  >  body text

Solve the problem of infinite loop caused by useEffect in React

<p>Why does this code produce an infinite loop in React. The useEffect here together with data and columnDataWithTaskProperty causes an infinite loop, but I don't know why</p> <pre class="brush:php;toolbar:false;">const useBoard = () => { const { data: columnData } = useGetColumnQuery(); const { data } = useGetTaskAccordingToStatus(); const [columnDataWithTaskProperty, setColumnDataWithTaskProperty] = useState( [] ); const [finalState, sFinalState] = useState([]); useEffect(() => { const allColumns = columnData?.data?.map((item) => ({ name: item.name, _id: item._id, tasks: [], })); setColumnDataWithTaskProperty(allColumns); }, [columnData]); useEffect(() => { console.log("meeee data deps"); const updatedColumns = columnDataWithTaskProperty.map((column) => ({ ...column, tasks: data.flat().filter((task) => task.status === column.name), })); sFinalState(updatedColumns); }, [columnDataWithTaskProperty, data]); return { finalState, }; };</pre> <p>Here is how I use useGetTaskAccordingToStatus to get the data. I used React Query to get the data. </p> <pre class="brush:php;toolbar:false;">const useGetTaskAccordingToStatus = () => { const { active_project } = useSelector(projectDataInStore); const userQueries = useQueries({ queries: statesOfTaskManager.map((status) => { return { queryKey: [status, active_project], queryFn: () => customAxiosRequestForGet("/task", { status, projectName: active_project, }), onSuccess: ({ data }) => { return data; }, }; }), }); const data = userQueries?.map((item) => item?.data?.data); return { data }; };</pre> <p><br /></p>
P粉018548441P粉018548441498 days ago486

reply all(1)I'll reply

  • P粉574695215

    P粉5746952152023-08-15 12:13:13

    I suggest you just use a use effect and remove columnDataWithTaskProperty to test sack, you can return it later. This is an example of my suggestion, but cannot be tested without real data.

    const useBoard = () => {
      const { data: columnData } = useGetColumnQuery();
      const { data } = useGetTaskAccordingToStatus();
      const [finalState, sFinalState] = useState([]);
    
      useEffect(() => {
        const allColumns = columnData?.data?.map((item) => ({
          name: item.name,
          _id: item._id,
          tasks: [],
        }));
          console.log("meeee data deps");
          const updatedColumns = allColumns.map((column) => ({
            ...column,
            tasks: data.flat().filter((task) => task.status === column.name),
          }));
          sFinalState(updatedColumns);
      }, [columnData, data]);
    
      return {
        finalState,
      };
    };

    reply
    0
  • Cancelreply