0

i want to set loading state to true using react useState.

what i am trying to do? i want to show a loading indicator when fetching a request. i do so by setting loading state to true just before request starts and set loading state to false soon after request ends.

below is my code,

export function useLoad() {
    const { refetch: refetchItems } = useGetItems();
    const { refetch: refetchOwnedItems } = useListOwnedItems();
    return async function() {
        await refreshCompany();
        refetchItems();
        refetchOwnedItems();
    };  
}

function useAnother(Id: string) {
    const [compId, setCompId] = React.useState(undefined);
    const [isLoading, setIsLoading] = React.useState(false);
    const comp = useCurrentComp(Id);
    const load = useLoad();
    if (comp && comp.id !== compId) {
        setCompId(comp.id);
        const prevCompId = compId !== undefined;
          if (prevCompId) {
              setIsLoading(true);
              console.log('loading state b4', isLoading); //this logs loading to false
              load().then(() => {
                  setIsLoading(false);
          });
      }
  }

}

function Parent () {
    useAnother('21s');
    return (
        //some jsx here
    );
}

Now the question is i am not sure why isLoading is false when logging it. it should be true.

could someone help me solve this. thanks.

amik
  • 5,613
  • 3
  • 37
  • 62
someuser2491
  • 1,848
  • 5
  • 27
  • 63
  • should you be passing `Id` to `useAnother`? – dpdenton Jun 09 '20 at 18:52
  • thanks but thats a typo in the question. – someuser2491 Jun 09 '20 at 18:55
  • 1
    Basically, `setState` _is_ working, but it's not going to be reflected until the next render. Hooks aren't magical enough to be able to change your local variables, just what the next return values are when you call `useState` on the next render. That's why you can't console.log that local variable and expect it to have changed. – Jacob Jun 09 '20 at 19:12

0 Answers0