Wrapping the app component with a context and getting the TypeError: (destructured parameter) is undefined

Viewed 72

I'm trying to wrap all components under the app in a context to provide the things that I want

(as You can see it's my UserContext component)

enter code here
 
import React, { useState, createContext, useContext } from 'react'

const Context = createContext();
export let useUserContext = () => useContext(Context);

export default function UsersContext({ children }) {
  const [users, setUsers] = useState();

  const createUser = (user) => {
    if (!user.name || !user.email || !user.password) return;
    const newUsers = [...users, user];
    setUsers(newUsers);
  }

  return (
    <Context.Provider value={{ users, createUser }}>


      {children}
    </Context.Provider>
  )
}

(it is my app component)

enter code here
  import Nav from "./components/nav/Nav";
  import Container from "./components/container/Container";
  import { BrowserRouter } from "react-router-dom";

  import UsersContext from "./components/contexts/UserContext";


  function App() {

    return (
      <UsersContext>
        <BrowserRouter>
          <Nav />
          <Container />
        </BrowserRouter>
      </UsersContext>
    );
  }

  export default App;

It's used to be like this in my projects and I didn't have any problem but now the error I'm getting "TypeError: (destructured parameter) is undefined" also says that it's because of the children in UserContext In my opinion it shouldn't happen maybe you can help me to find the problem I can't see.

enter image description here

2 Answers

Try: <Context.Provider value={[ users, { createUser } ]}>

instead of: <Context.Provider value={{ users, createUser }}>

edit:

also might try: instead of

    const newUsers = [...users, user];
    setUsers(newUsers);

do

    setUsers((currentUsers) => [...currentUsers, user]);

I found the problem. it was because of the useState. it was undefined and I was calling the property that related to useState at the UserContext.

Related