Easiest way to get react to communicate with backend

Easiest way to get react to communicate with backend
0

Im a new student working on an application for a charity website. im wanting to know the easiest way to get the frontend (react) to work with the backend (java) and a SQL database. Explanation of code would help also. thanks

React doesn’t specify anything to do with how to communicate over HTTP, it’s ui-only & completely agnostic.

So for example, for a component that fetches data when it mounts, you just use the browser fetch API, and fit it into how React works

const ExampleLoaderComponent = () => {
  const [isLoading, setIsLoading] = React.useState(false);
  const [error, setError] = React.useState(null);
  const [data, setData] = React.useState([]);

  // Keep the above values in sync, this will fire
  // every time the component rerenders, ie when
  // it first mounts, and then when any of the above
  // values change
  React.useEffect(() => {
    const makeRequest = async () => {
      setError(null);
      setIsLoading(true);
      try {
        const req = await fetch("http://example.com/api");
        const resp = await req.json();
        setData(resp);
      } catch (err) {
        setError(err);
      } finally {
        setIsLoading(false);
      }
    };

    if (!isLoading) makeRequest();
  }, [isLoading, data, error]);

  if (isLoading) return <LoadingComponent />;
  if (error) return <ErrorComponent text={error.message} />;

  return (
    <ul>
      {data.map(datum => <li>{datum}</li>)}
    </ul>
  );
};

(In class components you’d use this.state instead of the useState hook, and componentDidMount (+ possibly another lifecycle method) instead of the useEffect)

The above pattern has a few libraries available to remove the need to write that logic every time, for example https://github.com/zeit/swr

1 Like

Fetch is nice, and built-in on any modern browser that can handle React, but for real-world apps, I prefer axios. Has the same promise-based API as fetch, but it throws exceptions on 4xx and 5xx errors, which keeps you from having to manually check every call yourself. Also decodes json automatically, but that’s just gravy,