score:3

Accepted answer

first we create the context and pass it an initial value.

in order to fetch data and keep track of the returned value, we create a state inside the component. this component will manage the fetched data and pass it in the context provider.

to call an async function inside useeffect we need to wrap it and call it inside useeffect callback.

export const newcontext = createcontext({
    my_data: {} // initial value
});

export const newcontextprovider = props => {
    const [my_data, setmydata] = usestate({});

    useeffect(() => {
        const fetchmydata = async () => {
            const { datavalue } = await getdata();

            if (datavalue) {
                setmydata(datavalue);
            } else {
                // there was an error fetching the data
            }
        };

        fetchmydata();
    }, []);

    return (
        <newcontext.provider
            value={{
                my_data
            }}
        >
            {props.children}
        </newcontext.provider>
    );
};

to use this context in a component we use the usecontext hook. remember that this component needs to be wrapped by the provider we just created.

import react, { usecontext } from "react";
import { newcontext } from "./newcontext"; // the file where the context was created

export const mycomponent = props => {
    const { my_data } = usecontext(newcontext);

    return //...
};

let me know if something is not clear.


Related Query

More Query from same tag