DEV Community

Ahmet Kuslular
Ahmet Kuslular

Posted on

How to use React Context API with npm library

Hi. I am writing an admin project package with React. there are Auth operations in this package. I can access the conxtex by saying useAuth in the components in the package, but the context data does not come properly in the project using the package. I think there is a problem here due to packaging. Exactly how can I solve it, I don't want to take the Provider out and provide it in the components where the package is used.

AuthContext.ts

const initialAuthState = {
  user: null, // or any initial state you want
  isAuthenticated: false,
};

// Create a context with the initial state
export const AuthContext = createContext({
  authState: initialAuthState,
  setAuthState: () => {}
});

// AuthProvider component to provide auth state to its children
export const AuthProvider = ({ children }) => {
  const [authState, setAuthState] = useState(initialAuthState);

  useEffect(() => {
    // Example of updating state, replace this with your actual logic
    const fetchAuthState = async () => {
      // Simulate a fetch or any async operation to get auth data
      const newState = {
        user: { name: 'John Doe' },
        isAuthenticated: true,
      };
      setAuthState(newState);
    };

    fetchAuthState();
  }, []);

  return (
    <AuthContext.Provider value={{ authState, setAuthState }}>
      {children}
    </AuthContext.Provider>
  );
};

// Custom hook to use the auth context
export const useAuth = () => {
  const context = useContext(AuthContext);
  if (!context) {
    throw new Error("useAuth must be used within an AuthProvider");
  }
  return context;
};


//Container.tsx
export const Container = ({ children }) => {
  return (
    <AuthProvider>
      {children}
      <ExamplePage/>
    </AuthProvider>
  );
};

//ExamplePage.tsx
export const ExamplePage = () => {
  const authData = useAuth();

  //the data in this log is coming in correctly. 
  console.log('authData:', data);
  return (
    <div>
      example page
    </div>
  );
};


//app.tsx (other project)
import {Container} from 'my-package'

export const App = () => {
  return (
    <Container>
      <ListPage/>
    </AuthProvider>
  );
};


//listPage.tsx
import {useAuth} from 'my-package'

export const ListPage = () => {
  const authData = useAuth();


  console.log('authData:', data);   
  return (
    <div>
        List page
    </div>
  );
};

Enter fullscreen mode Exit fullscreen mode

Top comments (0)