Skip to content

Latest commit

 

History

History
71 lines (59 loc) · 2.61 KB

data-fetching.md

File metadata and controls

71 lines (59 loc) · 2.61 KB

Data Fetching

At a bare minimum you may want to use HTML5 Fetch API as an HTTP client utility for making Ajax request to the data API server. This API is supported natively in all the major browsers except for IE (note, that Edge browser does support Fetch).

React Starter Kit is pre-configured with whatwg-fetch polyfill for the browser environment and node-fetch module for the server-side environment (see src/createFetch.js), allowing you to use the fetch(url, options) method universally in both the client-side and server-side code bases.

In order to avoid the amount of boilerplate code needed when using the raw fetch(..) function, a simple wrapper was created that provides a base URL of the data API server, credentials (cookies), CORS etc. For example, in a browser environment the base URL of the data API server might be an empty string, so when you make an Ajax request to the /graphql endpoint it's being sent to the same origin, and when the same code is executed on the server, during server-side rendering, it fetches data from the http://api:8080/graphql endpoint (node-fetch doesn't support relative URLs for obvious reasons).

Because of these subtle differences of how the fetch method works internally, it makes total sense to pass it as a context variable to your React application, so it can be used from either routing level or from inside your React components as follows:

Route Example

{
  path: '/posts/:id',
  async action({ params, fetch }) {
    const resp = await fetch(`/api/posts/${params.id}`, { method: 'GET' });
    const data = await resp.json();
    return { title: data.title, component: <Post {...data} /> };
  }
}

React Component

import {useContext} from 'react';
import ApplicationContext from '../ApplicationContext';

function Post() {
  const {context} = useContext(ApplicationContext);
  return (
    <div>
      ...
      <a onClick={(event) => {
        event.preventDefault();
        const id = event.target.dataset['id'];
        // Use context.fetch to make it work in both server-side and client-side
        context.fetch(`/api/posts/${id}`, { method: 'DELETE' }).then(...);
      }}>Delete</a>
    </div>
  );
}

Related articles