cocacrave cocacrave - 5 months ago 44
Javascript Question

Loop through array async

I have this:

import React from 'react';
import { arr } from '../../../modules/ranks';
import { LOVE } from '../../components/svg/LOVE';

export const map = () => {
let col = 9;
let j = 9;
let k = 9;

return (
arr.map((rank, i) => {
if (i === col) {
col = col + j--;
if (j === 0) {
j = k--;
}
return [
<LOVE key={ rank } rank={ rank } />,
<div className="clearfix"></div>,
];
}
return (
<LOVE key={ rank } rank={ rank } />
);
})
);
};


Basically, I have a array of ranks (modules/ranks) that just a long list. But I need to add clearfix div on some of them as I map through to look presentable on the website.

What I have above works, but the array is long and will get longer so the page has to wait until it finishes looping before it displays the rest of the website.

I've been looking at async, and I tried to make it work but honestly its too hard for me to grasp...

Can someone help me use caolan/async? I read the docs many times...

Separate question for azium:
@azium
Thanks for referring me to your post. I tried to get it to work but I'm not sure.. it's not loading anything at the moment. The parent component is a simple render
<map />
.

import React, { Component } from 'react';
import { arr } from '../../../modules/ranks';
import { LOVE } from '../../components/svg/LOVE';

export class map extends Component {
constructor() {
super();
this.state = {
LOVE: [],
};
}

componentDidMount() {
this.load();
}

load() {
let col = 9;
let j = 9;
let k = 9;
setTimeout(() => {
arr.map((rank, i) => {
if (i === col) {
col = col + j--;
if (j === 0) {
j = k--;
}
return (
this.setState({
LOVE: this.state.LOVE.concat([
<LOVE key={ rank } rank={ rank } />,
<div className="clearfix"></div>,
]),
})
);
}
return (
this.setState({
LOVE: this.state.LOVE.concat(<LOVE key={ rank } rank={ rank } />),
})
);
});
});
}

render() {
return (
<div>
{ this.state.LOVE }
</div>
);
}
}

Answer

Here is an example of what I was describing within my comment on your post. I have created a component that imports your map and then executes asynchronously via setTimeout and subsequently calls the this.setState for the component.

import React from 'react';
import map from './map';

class MyComponent extends React.Component {
   constructor(props) {
     super(props);
     this.state = { loveElements: [] };
   }

   componentDidMount() {
     // async
     setTimeout(() => {
       const loveElements = map();
       this.setState({ loveElements: loveElements });
     }, 0);
   }

   render() {
     return (
       <div>
          {this.state.loveElements}
       </div>
     );
   }
}