govind jha
govind jha

Reputation: 107

How to get id from get api and use it in another api request

hi i am working on react with axios and using this api for get list https://api-test.com/api/get/all and want to use that id here for request axios.post('https://api-test.com/api/faqs')

 componentDidMount() {
  axios.get(`https://api-test.com/api/get/all`) **i want get id from here**
 .then(res => {
    const posts = res.data;
    this.setState({ posts });
   })
 }


    axios.post('https://api-test.com/api/faqs',
      { 
        getId: '1511', **And want use here**
        faqList:[
         { question: this.state.question, 
          answer: this.state.answer,
         }
        ]
      }
        )

Upvotes: 0

Views: 1134

Answers (1)

Shawn Yap
Shawn Yap

Reputation: 969

 axios.get(`https://api-test.com/api/get/all`) **i want get id from here**
 .then(res => {
    const posts = res.data;

    // Based on several assumptions: single obj returned, posts is never empty
    axios.post('https://api-test.com/api/faqs',
      { 
        getId: posts.id,
        faqList:[
         { 
           question: this.state.question, 
           answer: this.state.answer,
         }
        ]
      }
    )

    this.setState({ posts });
   })
 }

async/await example

async function functionName() {
  const {data: posts} = await axios.get(`https://api-test.com/api/get/all`);

  // Based on several assumptions: single obj returned, posts is never empty
  await axios.post('https://api-test.com/api/faqs', { 
      getId: posts.id,
      faqList:[
         { 
           question: this.state.question, 
           answer: this.state.answer,
         }
      ]
  })
}

functionName()

Upvotes: 1

Related Questions