1

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?

1 Answer 1

2

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>
    )
}
Sign up to request clarification or add additional context in comments.

4 Comments

Placing the axios call inside a useEffect with an empty dependencies array might be useful too, if you don't want to play the query with every render.
I've forgotten it. Thank you. I fixed.
Isn't result is going to be undefined, not null, if you are not giving useState a null default value ?
Yes, you're right. Sorry I didn't test enough. Thank you for check.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.