Sawtaytoes
3/20/2019 - 8:32 AM

React Parent Example

class Node extends Component {
  componentDidMount() {
    this.queueUpdate()
  }

  componentDidUpdate() {
    this.queueUpdate()
  }

  queueUpdate = () => {
    const { id } = this.props

    this
    .timeoutId = (
      setTimeout(
        () => {
          store
          .queue
          .push(id)
        },
        getRandomTimeout(),
      )
    )
  }

  render() {
    const {
      color,
      value,
    } = this.props

    return (
      <div
        style={{
          color,
        }}
      >
        {value}
      </div>
    )
  }
}
const initialState = {
  nodes: generateNodes(5000),
}

class Nodes extends Component {
  state = initialState

  constructor(props) {
    super(props)

    this.queue1 = []
    this.queue2 = []

    store
    .queue = this.queue1
  }

  componentDidMount() {
    this
    .intervalId = (
      setInterval(
        this.updateNodes,
        40,
      )
    )
  }

  updateNodes = () => {
    const { nodes } = this.state

    store
    .queue = (
      this.queue1.length > 0
      ? this.queue2
      : this.queue1
    )

    const tempQueue = (
      this.queue1.length > 0
      ? this.queue1
      : this.queue2
    )

    const updatedNodes = (
      tempQueue
      .reduce(
        (
          nodes,
          id,
        ) => {
          const nodeIndex = (
            nodes
            .findIndex(({
              id: nodeId,
            }) => (
              nodeId === id
            ))
          )

          return (
            nodes
            .slice(
              0,
              nodeIndex,
            )
            .concat({
              ...nodes[nodeIndex],
              color: getRandomColor(),
              value: getRandomValue(),
            })
            .concat(
              nodes
              .slice(nodeIndex + 1)
            )
          )
        },
        nodes,
      )
    )

    this
    .setState({
      nodes: updatedNodes,
    })

    tempQueue
    .splice(
      0,
      tempQueue.length,
    )
  }

  render() {
    const { nodes } = this.state

    return (
      nodes
      .map(({
        id,
        ...props
      }) => (
        <Node
          {...props}
          id={id}
          key={id}
        />
      ))
    )
  }
}