简体   繁体   中英

How to store response data from Axios to a variable in React Functional Component?

I'm using a React functional component. I want to store the data received from an API to a variable so that I can use it in the rest of the code.

const Component = (props) =>{
     let variable = {};

     Agent.API.get(props.id)
     .then((response)=>{
       variable = response.data })

     return( 
        <div><p>{variable.name}</p></div>
      )
}
export default Component;

This is something I want to achieve. How do I go about?

You want to use axios, so then set response in state.

import React, {useState, useEffect} from 'react'

export default (props) =>{
  const url = 'https://api.example.com'
  const [result, setResult] = useState(null)

  useEffect(() => {
    axios.get(url)
    .then((response)=>{
      setResult(response.data)
      // axios returns API response body in .data
    })
  }, []) // second param [] is a list of dependency to watch and run useEffect

  return( 
    <div><p>{result === null ? 'loading' : result.name}</p></div>
    )
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM