0

I'm trying to achieve the below functionality in CallGetAMIDetails using async mode and REST API call is there instead of Plain return

function CallGetAMIDetails(message) {
        return ["ABC" , "BDC"]
    }

and the code returns correctly on the line

<h2>{items}</h2>

Now I need to perform the REST API call modified the code to do the REST call

import React, { useEffect, useState } from "react";

import { DashboardLayout } from "../components/Layout";
import Select from "react-select";
import { DataGrid } from "@material-ui/data-grid";

const options = [
  { value: "ami-abc*", label: "ami-abc" },
  { value: "ami-xyz*", label: "ami-xyz" },
];

const DiscoverAMIPage = () => {
  function CallGetAMIDetails(message) {
    (async () => {
      const res = await fetch("http://localhost:10000/details/" + message).then((response) => response.json());
      return res;
    })();
  }

  const [message, setMessage] = useState("");
  const [items, setItems] = useState([]);

  return (
    <DashboardLayout>
      <h2>Discovered AMI</h2>
      <Select
        onChange={(e) => {
          setMessage(e.value);
          setItems(CallGetAMIDetails(e.value));
        }}
        options={options}
      />
      <h2>{items}</h2>
    </DashboardLayout>
  );
};

export default DiscoverAMIPage;

This time the call to <h2>{items}</h2> return nil, which is due to promise is not evaluated,

I'm not sure what I need to change to get the response evaluated in the return call and display it properly in UI

AKX
  • 152,115
  • 15
  • 115
  • 172
anish
  • 6,884
  • 13
  • 74
  • 140
  • 2
    Don't confuse function components with functional code. – Quentin Aug 16 '21 at 16:13
  • You need to call the API in a side effect like `useEffect` and set the state once API data is received to re-render the screen & display the data. – Rajendran Nadar Aug 16 '21 at 16:14
  • This might help you https://stackoverflow.com/a/68784761/5519872 – Rajendran Nadar Aug 16 '21 at 16:16
  • Call `setItems` *inside* of `CallGetAMIDetails` where you have the `res` value. Otherwise you're just setting `items` to the *promise*, not the *result*. – David Aug 16 '21 at 16:16
  • Calling `setItems` inside `CallGetAMIDetails` will result in this error Invalid Hook Error https://stackoverflow.com/questions/68804783/reactjs-invalid-hook-call-hooks-can-only-be-called-inside-of-the-body-of-a-fu – anish Aug 16 '21 at 17:02

0 Answers0