Search code examples
javascriptajaxreactjspurely-functional

How to handle Ajax in pure function components in react?


I'm trying to write all my components as pure functions, but now I run into trouble. I have a component that looks somewhat like below. Trouble is, the result of the ajax request causes a rerender, which causes another ajax request, and there you have your infinite loop. How to properly handle this?

const PageProductFunnel = function (props) {
  const agent = ajaxagent;
  var list = [];

  agent.get(`https://mylist.com/${productSKU}`).then((res) => {
    list = res.data;
  });

  return (
    <div>
      <div className="cell">
        <article className="article">
          <h1 className="article-title">{product.name}</h1>
          <FunnelStep {...props} list={list} />
          <ButtonAddToCart product={product} />
        </article>
      </div>
    </div>
  );
};

Solution

  • There are few approaches you can take:

    1. fetch async data globaly, not inside render of the component
    2. Do not use pure function for this component, and hook async into life cycle methods