CreateContext for a variable that is in custom hook (React)

41 views Asked by At

How can I create a context for isLoading so I can display something on the screen based on it's state in other component? In other words - UseApi (custom hook) should return only data, fetchData but I want to access the state of isLoading in other components via createContext which will be ONLY for it. Thanks :)

import React, { useState } from "react";

export const UseApi = (initialState) => {

    const[data, setData] = useState(initialState || {});
    const [isLoading, setIsLoading] = useState(true);

    const fetchData = async (url) => {
        setIsLoading(true)
        try {
            const response = await fetch(url);
            if(!response.ok){
                throw new Error('Network issue')
            }
            const data = await response.json();
            setData(data);
        } catch (error) {
            console.log(error)
        }
        finally{
            setIsLoading(false)
        }
        
    }

    return{
        data,
        fetchData,
    }
}

export default UseApi;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

0

There are 0 answers