简体   繁体   中英

Updating a global variable from within a function

I am defining two variables:

var information;
var secondary_information;

I update these variables within my function:

async function fetchInfo() {
var num = Math.floor(Math.random() * 20 + 1);

const url = `https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=${pos.current.coords.latitude},${pos.current.coords.longitude}&radius=12000&type=restaurant&key=${key}`;

await fetch(url)
  .then((response) => response.json())
  .then((data) => setSearchResponse(data))
  .then(console.log("api request fired."));

let place_id = searchResponse.results[num].place_id;


const secondary_url = `https://maps.googleapis.com/maps/api/place/details/json?fields=formatted_phone_number,opening_hours,formatted_address&place_id=${place_id}&key=${key}`;

await fetch(secondary_url)
  .then((response) => response.json())
  .then((data) => setsecondarySearchResponse(data))
  .then(console.log("secondary api request fired."));

 information = {
  name: searchResponse.results[num].name,
  open_now: searchResponse.results[num].opening_hours.open_now,
  rating: searchResponse.results[num].rating,
  price: searchResponse.results[num].price_level
};

 secondary_information = {
  phone_number: secondarySearchResponse.result.formatted_phone_number,
  daily_hours: secondarySearchResponse.result.opening_hours.weekday_text,
  address: secondarySearchResponse.result.formatted_address
};
}

When I console log the variables from within the function it works as intended.

I am trying to pass the variables down as props to a react component but it keeps passing an empty object instead:

return (
<div className="App">
  <Filters />
  <Button variant="primary" onClick={fetchInfo}>
    Randomizer
  </Button>{" "}
  <Result info={information} />
</div>
);

Additionally, I have no clue if this is the correct way I should be going about making these API calls and storing them into state but this is the way that made sense to me. Any feedback is greatly appreciated.

You should be using useState in react to store your variables. how to use

Creating

const [information, setInformation] = useState(null);

Updateing

setInformation({
  name: searchResponse.results[num].name,
  open_now: searchResponse.results[num].opening_hours.open_now,
  rating: searchResponse.results[num].rating,
  price: searchResponse.results[num].price_level
})

Then passing the state to props should stay the same.

<Result info={information} />

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