Home > Software engineering >  Route endpoint doesn't hit with React Router V6 and Context API
Route endpoint doesn't hit with React Router V6 and Context API

Time:09-05

I'm using React 18.2.0 with react-router-dom version 6.3.0 In my app, I want to use Context API for state management. below is my context creation code:

export const QuoteContext = React.createContext();

export const QuoteContextProvider = ({ children }) => {
  const [quotes, setQuotes] = useState([]);
  const [isLoading, setIsLoading] = useState(false);

  const addQuote = (quoteData) => {
    // logic to add a quote to state
  };

  <QuoteContext.Provider value={{ quotes, addQuote }}>
    {children}
  </QuoteContext.Provider>;
};

Below is my App.JS file where I'm using routing:

function App() {
  return (
    <>
      <Header />
      <QuoteContextProvider>
        <Routes>
          <Route path="/" element={<Home />}></Route>
          <Route path="/add" element={<NewQuote />}></Route>
          <Route path="/:quote" element={<Details />}></Route>
        </Routes>
      </QuoteContextProvider>
    </>
  );
}

Below is my index.js

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
  <React.StrictMode>
    <BrowserRouter>
      <App />
    </BrowserRouter>
  </React.StrictMode>
);

With all this setup, when I run the application only the <Header> component is shown on the browser screen, no other route endpoint is activated. Even if I change the browser URL manually, nothing happens. What am I missing here?

CodePudding user response:

QuoteContextProvider is the problem. You are wrapping everything in it and yet not returning anything. Try this out:

export const QuoteContext = React.createContext();

export const QuoteContextProvider = ({ children }) => {
  const [quotes, setQuotes] = useState([]);
  const [isLoading, setIsLoading] = useState(false);

  const addQuote = (quoteData) => {
    // logic to add a quote to state
  };

  return <QuoteContext.Provider value={{ quotes, addQuote }}>{children}</QuoteContext.Provider>;
};
  • Related