import React from "react";
import PropTypes from "prop-types";
import SVG from "./assets/sprite.svg";
import s4e from "svg4everybody";
import cn from "classnames";
import "./_Sprite.scss";

export default class Sprite extends React.Component {
  static loaded = false;
  static loading = [];

  static propTypes = {
    id: PropTypes.string,
    viewBox: PropTypes.string
  };

  state = {
    ready: Sprite.loaded
  };

  req = typeof XMLHttpRequest !== "undefined" && new XMLHttpRequest();

  componentDidMount() {
    if (this.req && Sprite.loaded === false) {
      Sprite.loading.push(this);

      if (Sprite.loading.length > 1) {
        return;
      }

      this.req.open("GET", SVG, true);
      this.req.send();
      this.req.onload = () => {
        const div = document.createElement("div");
        div.innerHTML = this.req.responseText;
        div.style.display = "none";
        document.body.insertBefore(div, document.body.childNodes[0]);
        Sprite.loaded = true;

        if (this.unmounted !== true) {
          this.setState({ ready: true }, s4e);
          Sprite.loading.forEach(c => c.setState({ ready: true }));
        }
      };
    }
  }

  componentWillUnmount() {
    this.unmounted = true;
  }

  render() {
    const { viewBox, id, className, ...rest } = this.props;
    const { ready } = this.state;

    // Display Placeholder
    if (!ready) {
      return (
        <span className={cn("svg-placeholder", "svg-sprite", className)} />
      );
    }

    return (
      <svg
        role="img"
        {...rest}
        viewBox={viewBox}
        className={cn("svg-sprite", className)}
      >
        <use xlinkHref={"#" + id} />
      </svg>
    );
  }
}

@@ -1112,35 +1112,110 @@
  =%3E 
-c.setState(%7B ready: true %7D)
+%7B%0A            if (!c.unmounted) %7B%0A              c.setState(%7B ready: true %7D);%0A            %7D%0A          %7D
 );%0A 

fix unmounted component warning on Sprite