Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React & dealing with asynchronous state

Our React application talks to an API via a library that heavily depends on promises.

We might for example pass an "User resource" around. When we render a User component, this component gets access to the users' properties by calling await User.get() in componentDidMount.

The implication is that many (if not most) of our components all need to have a ready state property, and most of them need to both deal with the case of a first render, and render after the user properties have been received.

This feels clunky. One idea we had was to create components specifically responsible for doing the loading of data, and a second set of "view" components only responsible for rendering after the loading is complete.

One issue here is that the "view" components are often also forms and need to communicate state changes back up the tree.

Not hard to do, but I am mainly curious if there are known good patterns for tackling this sort of thing, or prior art I can base this off. Alternatively, I will also take other suggestions on how to deal with this pattern.

like image 525
Evert Avatar asked Oct 27 '22 07:10

Evert


1 Answers

I am using this component with redux

import React, { useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";
import { Spinner } from "@blueprintjs/core";

export default ({ action, selector, component, errorComponent }) => {
  const dispatch = useDispatch();

  useEffect(() => {
    dispatch(action());
  }, [dispatch, action]);

  const DispatchFetch = () => {
    const { data, isRequesting, error } = useSelector(selector());
    if (!isRequesting && data) {
      const Comp = component;
      return <Comp data={data}></Comp>;
    } else if (error) {
      if (errorComponent) {
        const ErrorComp = errorComponent;
        return <ErrorComp error={error}></ErrorComp>;
      }
      return <div>{error}</div>;
    }
    return <Spinner></Spinner>;
  };

  return <DispatchFetch></DispatchFetch>;
};
like image 152
anerco Avatar answered Nov 12 '22 18:11

anerco