0

I have been trying to create a table from an array of objects. I'm able to console the data inside the async function. But I couldn't console it outside.

My code :

useEffect(() => {
  listingCampaignsModels()
}, []);


async function listingCampaignsModels() {
    const apiData = await DataStore.query(Campaign);
    console.log(apiData);
    console.log(typeof(apiData));
    return apiData;
  };

When I tried to console apiData outside, it returns apiData is not defined error.

The data looks like this :

[Model, Model, Model, Model, Model, Model]

Each Model looks like :

-> 1: Model {id: 'c40d6b22-840f-467a-909c-7b2b19960ffb', campaignOwner: 'eumagnas', campaignName: "mollitlab", startDate: "2022/08/15", endDate: "2022/10/25", expectedRevenue: 25, budgetedCost: 27, actualCost: 28}

I want loop through all the Models and create a table as :

Campaign Owner Campaign Name Start Date End Date Expected Revenue Budgeted Cost Actual Cost
eumagnas mollitlab 2022/08/15 2022/10/25 25 27 28
Phil
  • 157,677
  • 23
  • 242
  • 245
  • 1
    You need to set the data into some state, eg if you have `const [ campaigns, setCampaigns ] = useState([])`, then you would use `listingCampaignsModels().then(setCampaigns)` – Phil Jan 18 '22 at 04:54

1 Answers1

-1

You need to use useState() hook to save the data as campaign state.

const [campaigns, setCampaigns] = useState([]);

useEffect(() => {
  listingCampaignsModels()
}, []);


async function listingCampaignsModels() {
    const apiData = await DataStore.query(Campaign);
    console.log(apiData);
    setCampaigns(apiData);
  };
Rahul Kumar
  • 3,009
  • 2
  • 16
  • 22