title: React TypeScript: How to call an api and set state each time the route changes
body: <p>useEffect fires perfectly each time I change the route, When I call the API from within useEffect, and then try to set state with the result I get the error <code>Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.</code></p>
  
  <p>I have tried invoking <code>getPrice</code> with a self-invoking function and nothing changes, I still get the same error.</p>
  
  <p>Should I be using <code>Suspense</code> ??</p>
  
  <pre><code>import React, { useContext, useEffect, useState } from 'react';
  const Calc: React.FC = () =&gt; {
  
    interface StateInterface {
      priceUsd: number;
    }
  
    const [price, setPrice] = useState&lt;StateInterface&gt;({
      priceUsd: 0,
    });
  
    useEffect(() =&gt; {
      const getPrice = async () =&gt; {
        const response = await fetch('http://localhost:9999/price', {
          body: JSON.stringify({
            jwtToken: localStorage.getItem('jwtToken'),
          }),
          headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
          },
          method: 'POST',
        });
        if (response.status !== 400) {
          const content = await response.json();
          const priceUsd = content.price[0].priceUsd;
          setPrice({ priceUsd });
        }
      };
      getPrice();
    }, []);
  
    return (
      &lt;div&gt;Calc&lt;/div&gt;
    )
  }
  export { Calc };
  </code></pre>
  
  <p>This calc component gets loaded in the router like this</p>
  
  <pre><code>import React, { useReducer } from 'react';
  import { BrowserRouter, Route, Switch } from 'react-router-dom';
  import { globalContext, setGlobalContext } from './components/shell/context';
  import { Layout } from './components/shell/layout';
  import { defaultState, globalReducer } from './components/shell/reducer';
  import { Calc } from './routes/calc';
  import { NotFound } from './routes/not-found';
  
  export function Router(): JSX.Element {
    const [global, setGlobal] = useReducer(globalReducer, defaultState);
  
    return (
      &lt;setGlobalContext.Provider value={{ setGlobal }}&gt;
        &lt;globalContext.Provider value={{ global }}&gt;
          &lt;BrowserRouter&gt;
            &lt;Route
              render={({ location }) =&gt; (
                &lt;Layout location={location}&gt;
                  &lt;Switch location={location}&gt;
                    &lt;Route exact path='/' component={Calc} /&gt;
                    &lt;Route component={NotFound} /&gt;
                  &lt;/Switch&gt;
                &lt;/Layout&gt;
              )}
            /&gt;
          &lt;/BrowserRouter&gt;
        &lt;/globalContext.Provider&gt;
      &lt;/setGlobalContext.Provider&gt;
    );
  }
  </code></pre>