Search code examples
javascriptarraysreactjsaxioses6-promise

How can i display data of an api one after another on the basis of id in react js.?


So basically what iam trying to do is to get data from an api using axios get one after another for example Q1 what is your name (user answers it and then clicks next) Next Q2 what is your hobby(user answers it and then clicks next) than Q3,4,5,6 etc i want to display limited amount of data from an api which consists of array of 63 questions.I want o build a questionare where questions are displayed after the user answers the previous one.Here you can see my apis containing data

Mycode is

import React, { Component } from 'react';
import Axios from 'axios'
import ReactDOM from "react-dom";

class Questionare extends Component {
  state = {
    items: []
  };


componentDidMount() {
  Axios.get('http://leaty-dev.azurewebsites.net/')
  .then(response => {
      console.log(response);
      this.setState({ items: response.data.result.items });
  })
  .catch(error => {
    console.log(error);
  });
}

    render() { 
      const { items } = this.state;
       return (
        <div>
          <button className="btn" >Click</button>
          <ul>
            {items.map(item => (
          <li key={item.id}>{item.pqDetail}</li>
        ))}
          </ul>
          </div>
       )
    }

}

export default Questionare;

Solution

  • Pick items one after the other and set as currentItem and then render currentItem to view.

    mport React, { Component } from 'react';
    import Axios from 'axios'
    import ReactDOM from "react-dom";
    
    class Questionare extends Component {
      state = {
        items: [],
        currentItem: null,
        index: 0
      };
    
    
    componentDidMount() {
      Axios.get('http://leaty-dev.azurewebsites.net/api/services/app/PersonalityQuestioner/GetAllPersonalityQuestioner')
      .then(response => {
          console.log(response);
          this.setState({ items: response.data.result.items, currentItem: response.data.result.items[0], index: 0 });
      })
      .catch(error => {
        console.log(error);
      });
    }
    
    handleNext = () => {
        const { index, items } = this.state;
        const nextQuestion = index + 1;
    
        this.setState({ currentItem: items[nextQuestion], index: nextQuestion });
    }
    
        render() { 
          const { currentItem } = this.state;
           return (
            <div>
              <button className="btn" onClick={this.handleNext}>Next</button>
              <ul>
              <li key={currentItem.personalityQuestionerCategory.id}>{currentItem.pqDetail}</li>
              </ul>
              </div>
           )
        }
    
    }
    
    export default Questionare;