2

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
}

1 Answer 1

2

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>
  );
}

Sign up to request clarification or add additional context in comments.

6 Comments

I did what you suggested. got another error Uncaught TypeError: object null is not iterable (cannot read property Symbol(Symbol.iterator))
Is that on a different line? Sounds like a different problem
on the same line
Updatet the answer
thanks! issue solved
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.