Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

setup context api

//# Contect.js 
import { useEffect, useState, createContext } from "react";

export const CharityContext = createContext();

export const CharityContextProvider = ({ children }) => {
  const loki = "chaulagain";
  return <CharityContext.Provider value={{ loki }}>{children}</CharityContext.Provider>;
};

//# app.js
import { CharityContextProvider } from "../context/Context";

function MyApp({ Component, pageProps }: AppProps) {
  return (
    <CharityContextProvider>
      <Component {...pageProps} />
    </CharityContextProvider>
  );
}

export default MyApp;

//# fetch data in any file
import React, { useContext } from "react";
import { CharityContext } from "../context/Context";

function Index() {
  const { loki } = useContext(CharityContext);
  console.log(loki); //-->Result:Chaulagain
  return <div>Index</div>;
}

export default Index;


 
PREVIOUS NEXT
Tagged: #setup #context #api
ADD COMMENT
Topic
Name
9+4 =