Home > Blockchain >  for loop only iterating twice with axios
for loop only iterating twice with axios

Time:09-28

const [Datalist,setDatalist] = useState([]);

  useEffect(() => {
  axios.get( 'http://0.0.0.0:8000/api/v1/questions/history/1')
  .then(response => {
    const questions = response.data;
    const datalist = [];
    for (let i = 0; i < questions.length - 1; i  ) {
      const data = new Object();
      data.isExpanded = false;
      data.question_id = questions[i].id;
      data.question = questions[i].content;
      data.type = questions[i].type;
      data.commentType = questions[i].comment_type;
      data.answer = [];
      datalist.push(data);
    }
    setDatalist(datalist);
  });
  },[]);

I have three questions in my database currently. The for loop should be iterating through 0 to 2, however, it is only iterating twice. And I'm also having problems putting the data into Datalist. Anybody know where the issue is?? Thanks in advance!!

CodePudding user response:

Change your for loop to this:

for (let i = 0; i < questions.length; i  )

CodePudding user response:

Since you are iterating over each question you receive, you could use the map-method (if your environment supports ES6-Syntax - but since you're using react, it most likely dooes).

From the MDN Docs:

The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.

With map, your code could look like this:

(Also note the removal of const data = new Object();. you can initialize an object and assign its properties/values at the same time)

const [Datalist,setDatalist] = useState([]);

useEffect(() => {
  axios.get( 'http://0.0.0.0:8000/api/v1/questions/history/1')
  .then(response => {
    const questions = response.data;
    const datalist = questions.map(question => {
      return {
        isExpanded: false;
        question_id: question.id;
        question: question.content;
        type: question.type;
        commentType: question.comment_type;
        answer: [];
      };
    });
    setDatalist(datalist);
  });
},[]);
  • Related