reactor
reactor

Reputation: 1931

how to maintain state of an ajax request and its loading state of a React component after it unmounts

I was wondering if there's a way to persist state of a component that will unmount and possibly remount in the example of a dropdown that has a download option, which will then close the dropdown upon selection, which will cause the option to unmount and a spinner will load.

Right now, I'm keeping all of the state of the related dropdown option in its parent and passing it back down to the option via props and would rather have that logic stored in a custom hook or something cleaner.

const Parent = () => {
  const [isLoading, setIsLoading] = useState(false);
  const [setDataToDownload, dataToDownload] = useState();
  return (
    <>
      {isLoading && <Spinner />}
      <Dropdown>
        {({ close }) =>
          options.map(op => (
            <ChildOption
              isLoading={isLoading}
              setDataToDownload={setDataToDownload}
              dataToDownload={dataToDownload}
              setIsLoading={setIsLoading}
              close={close}
              op={op}
            />
          ))
        }
      </Dropdown>
    </>
  );
};

const ChildOption = ({ close, isLoading, setIsLoading }) => {
  return (
    <div
      onClick={async () => {
        close();
        setIsLoading(true);
        const data = await fetchSomeStuff();
        setDataToDownload(data);
        setIsLoading(false);
      }}
    >
      {op.name}
    </div>
  );
};

Upvotes: 0

Views: 80

Answers (1)

user9408899
user9408899

Reputation: 4540

if there's a way to persist state of a component that will unmount.

States of components are destroyed, when they are unmounted. So, you cannot access or retrieve state of an unmounted component. Unless, you store the state somewhere else.

You can use Redux, as a global state. You can dispatch an action from componentWillUnmount lifecycle method to store your current state in Redux store. And, you can retrieve it back in componentDidMount lifecycle method.

Other than Redux, you can use the localStorage to store component's state. Make use of componentWillUnmount and componentDidMount lifecycle methods as I explained above.

Upvotes: 0

Related Questions