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