0

Please, how can I get summaryfrom inside async fetchData to be exported to Layout? (knowing that summary is 5-elements array)

import { useRouter } from "next/router";
import Layout from '../../components/layoyt';
import Campaign from '../../components/campaign';

const Post = () => {
    const router = useRouter();
    const { address } = router.query;
    const campaign = Campaign(address);

    const fetchData = async () => {
        try {
            const summary = await campaign.methods.getSummary().call();
            // Handle the summary data here
            console.log(summary);
        } catch (error) {
            // Handle any errors that may occur during the API call
            console.error(error);
        }
    }
    fetchData();

    return (
        <Layout>
            <p>Post : {address}</p>
            {summary[0]}
        </Layout>
    )
}

export default Post;
Rego
  • 1,118
  • 1
  • 18
  • 40

1 Answers1

2

You can use useState at the top of your component.

Add const [summary, setSummary] = useState([]) above useRouter hook. And don't forget to import it from react. And after that instead of console.log(summary) write setSummary(summary). And it should work :)

Here you can see code below:

import { useState, useEffect } from "react";

const Post = () => {
const [summary, setSummary] = useState([]);
...
useEffect(() => {
    const fetchData = async () => {
        try {
            const summary = await campaign.methods.getSummary().call();
            // Handle the summary data here
            setSummary(summary);
        } catch (error) {
            // Handle any errors that may occur during the API call
            console.error(error);
        }
    };
    fetchData();
}, []);

P.S Also it's better to wrap async code with useEffect.