Error is
Uncaught TypeError: object null is not iterable (cannot read property Symbol(Symbol.iterator))
import React from 'react';
import { NavigationBar } from './components/header/Navbar';
import {Outlet} from "react-router-dom"
export default function App(){
const [account, setAccount] = React.useState<string>('')
return (
<div className="App">
<NavigationBar />
<Outlet context={[account, setAccount]}/>
</div>
);
}
I am getting error on the line const {account, setAccount} = useOutletContext();
Below is the snippet of code where account and setAccount is needed.
import { useOutletContext } from "react-router-dom";
const NavigationBar:React.FC = () => {
const [account, setAccount] = useOutletContext();
// rest of the code
}
CodePudding user response:
You are using useOutletContext
as an object, but it is an array. So the {}
should be a []
in this case.
Change it to
const [account, setAccount] = useOutletContext();
Docs: https://reactrouter.com/docs/en/v6/api#useoutletcontext
Now that you're getting the Symbol.iterator error: you are supposed to set the context on a parent route and consume the context on an inner route. In your current code you are setting and consuming it on the same level.
See this codesandbox for a working example: https://codesandbox.io/s/useoutletcontext-eg1fxb
Below is the code from the sandbox for complete reference
import React from "react";
import { Outlet, Routes, Route, BrowserRouter } from "react-router-dom";
import { useOutletContext } from "react-router-dom";
const Dashboard = () => {
const [account, setAccount] = React.useState("ACCOUNT-NAME");
return (
<div className="App">
<h1>Outer route</h1>
<Outlet context={[account, setAccount]} />
</div>
);
};
const DashboardInner = () => {
const [account, setAccount] = useOutletContext();
return <div>Account: {account}</div>;
};
export default function App() {
return (
<BrowserRouter>
<Routes>
<Route path="/" element={<Dashboard />}>
<Route path="/" element={<DashboardInner />} />
</Route>
</Routes>
</BrowserRouter>
);
}