Home > other >  Using createContext to share API data globally through React app
Using createContext to share API data globally through React app

Time:10-19

I'm currently working on an app that fetches data from an API and displays it on the front-end. I've got the data coming up correctly when I print it to the console (so I know fetching the data isn't an issue) and I want to be able to use this data globally across different components. I'm aiming to use createContext to do this but haven't figured it out yet. Here's my code so far:

useFetch.ts

export const useFetch = (url: string) => {
    const [fetchedData, setFetchedData] = useState(null);
    const [loaded, setLoaded] = useState(false);

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

    const getAllFetchedData = async () => {
        await axios.get(url).then((response) => {
            const data = response.data;
            setFetchedData(data)
            setLoaded(true)
        })
            .catch(error => console.error(`Error: ${error}`));
    }

    return [loaded, fetchedData];
}

DataProvider.tsx

type PostProviderProps = {
    children: React.ReactNode
}

export default function DataProvider({ children }: PostProviderProps) {
    const [loaded, data] = useFetch(`https://jsonplaceholder.typicode.com/posts`)
    return (
        <PostContext.Provider value = {[loaded, data]}>
            {children}
        </PostContext.Provider>
    )
}

DataContext.ts

type PostContextType = {
    userId: number;
    id: number;
    title: string;
    body: string;
}

const PostContext = createContext<PostContextType>({} as PostContextType)
export default PostContext

If anybody could help it'd be really appreciated

  • Related