Replies: 1 comment
-
You can achieve this either with a state management library like zustand or redux or via the context api directly e.g import React, { createContext, useState, useContext } from 'react';
const ErrorContext = createContext(null);
export function ErrorProvider({ children, error }) {
const [errorState, setError] = useState(error);
return (
<ErrorContext.Provider value={{ error: errorState, setError }}>
{children}
</ErrorContext.Provider>
);
}
export function useError() {
const context = useContext(ErrorContext);
if (!context) {
throw new Error('useError must be used within ErrorProvider');
}
return context;
} Wrap your app with the ErrorProvider at a high level, passing any initial error from your data fetching logic: import { ErrorProvider } from './ErrorContext';
function App() {
const [data, setData] = useState(null);
const [error, setError] = useState(null);
// ... data fetching logic (handle errors and update setError)
return (
<ErrorProvider error={error}>
{/* Your app components here */}
</ErrorProvider>
);
} In your navbar component, access the error state and conditionally render content: import React, { useContext } from 'react';
import { useError } from './ErrorContext';
function Navbar() {
const { error } = useError();
return (
<nav>
{/* Standard navbar content */}
{error && <p>Error: {error.message}</p>}
</nav>
);
} |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
I have a navbar that wraps the entire app.
I want to change the navbar if an error occurs.
Is there anyway to acheive this ?
Beta Was this translation helpful? Give feedback.
All reactions