Where do generic fetch() calls go in React / Redux?

Viewed 42

By generic I mean a fetch() call is not tied to a single component.

Where should I put this fetch() call? Currently I have it in the top level React component. I simply return null and it does not render anything but it does run and populate redux.

This method seems a bit hacky and was wondering if React provides a way, or is there a common design pattern, to say fetch data that is not tied to a single component.

In general how should I do this?

I would like to write a simple JavaScript function, and then disptach() the data to redux, but React will not let me use dispatch inside a non-rendered JS function.

In general how does one write fetch() when the fetch() is not tied to a single component, and also when this fetch() needs to use dispatch().

// hacky way
import React                from 'react';
import { useDispatch }      from 'react-redux';

export default () => {

  const dispatch = useDispatch();
  // run fetch() here
  return null;
};
0 Answers
Related