Search code examples
reactjsreact-querymui-xmui-x-charts

useQuery isLoading value, doesn't refresh if condition rendering in react function


I'm trying to achive following situation in my Dashboard component - when useQuery finally load data from server, then I want to display component BarChart in my application, here's my code:

import { BarChart } from "@mui/x-charts/BarChart";
import { useQuery } from "@tanstack/react-query";
import { getDashboardData } from "../services/apiDashboard";
import { getFormattedToShortDayMonth } from "../core/helpers/date.helper";

export default function Dashboard() {
  const { isLoading, data } = useQuery({
    queryKey: ["fetchDashboardData"],
    queryFn: getDashboardData,
    retry: false,
  });

  console.log(isLoading);

  return (
    <>
      {!isLoading ?? (
        <BarChart
          height={300}
          series={[
            {
              data: data?.expenses.map((x) => x.amount),
              label: "Test",
              id: "Test",
            },
          ]}
          xAxis={[
            {
              data: data?.expenses.map((x) => {
                const formattedDate = new Date(x.date);
                return getFormattedToShortDayMonth(formattedDate);
              }),
              scaleType: "band",
            },
          ]}
        />
      )}
    </>
  );
}

This doesn't refresh component, so I don't see BarChart data (I see in output that isLoading change status from true to false). But if I have following condition defined:

return (
    <>
      {isLoading == false ? (
        <BarChart
          height={300}
          series={[
            {
              data: data?.expenses.map((x) => x.amount),
              label: "Test",
              id: "Test",
            },
          ]}
          xAxis={[
            {
              data: data?.expenses.map((x) => {
                const formattedDate = new Date(x.date);
                return getFormattedToShortDayMonth(formattedDate);
              }),
              scaleType: "band",
            },
          ]}
        />
      ) : (
        ""
      )}
    </>
  ); 

Then everything works as expected. Is there any limitation to use short if condition with useQuery or what is the reason of described problem ?


Solution

  • Instead of ??, you should use &&. For example:

    return (
          {!isLoading &&  // (your components)
    )
      
    

    The reason you need to do it this way is that ?? only checks for undefined and null, but !isloading will always be either true or false, never undefined/null