Home > Back-end >  How to get object out of React component
How to get object out of React component

Time:11-25

I am making an weather app with API, I am successfully receiving the data with API in the function but I am not able to take it out of the function

here is the code

import React, {useState} from 'react'
import {Text, View} from 'react-native'
const axios = require('axios');


let HomeScreen =() => {
  let key = "XXXX"
  axios.get(`https://api.weatherapi.com/v1/current.json?key=${key}&q=London&aqi=no`)
  .then(function (response) {
    // handle success
    console.log(response)
  })
  return(
    <Text>This is {response}</Text>
  )
}

export default HomeScreen

CodePudding user response:

If you want to simply return data from the API use a normal JS function, not a React component.

function getData() {
  return axios(`https://api.weatherapi.com/v1/current.json?key=${key}&q=London&aqi=no`)
}

It will return a promise which you can then use somewhere else.

async main() {
  const data = await getData();
}

If you want your component to render data retrieved from the API you need to do things differently.

Use useEffect to run once when the component is mounted, and use useState to store the data once it's been retrieved. The state will then inform the JSX how to render.

Note that the response from the API is an object with location and current properties. You can't just add that to the JSX because React won't accept it. So, depending on what value you need from the data, you need to target it specifically.

Here's an example that returns the text value from the condition object of the current object: "It is Sunny".

const { useEffect, useState } = React;

function Example() {

  // Initialise your state with an empty object
  const [data, setData] = useState({});

  // Call useEffect with an empty dependency array
  // so that only runs once when the component is mounted
  useEffect(() => {

    // Retrieve the data and set the state with it
    async function getData() {
      const key = 'XXX';  
      const data = await axios(`https://api.weatherapi.com/v1/current.json?key=${key}&q=London&aqi=no`)
      setData(data.data);
    }

    getData();

  }, []);

  // If there is no current property provide a message
  if (!data.current) return <div>No data</div>;

  // Otherwise return the current condition text
  return (
    <p>It is {data.current.condition.text}</p>
  );

}
  • Related