Reputation: 23
I'm trying to use the Context Api to save the user data that comes from the firebase api, but when I get these values in the component Index, it always returns the error: TypeError: Object is not iterable (cannot read property Symbol(Symbol.iterator))
Below is my code
Where do I create the Context
import React, { createContext, useState } from "react";
const Context = createContext();
function AuthProvider({children}) {
const [userLogin, setUserLogin] = useState({});
return (
<Context.Provider value={{ userLogin, setUserLogin }} >
{ children }
</Context.Provider>
);
}
export { Context, AuthProvider }
Route File
<React.StrictMode>
<BrowserRouter>
<AuthProvider>
<Routes>
<Route path='/' element={<Login />} />
<Route path='/cadastrar' element={<Register />} />
<Route path='/recuperar-senha' element={<Recovery />} />
<Route path='/anuncios' exact element={<Index />} />
</Routes>
</AuthProvider>
</BrowserRouter>
</React.StrictMode>
Here where I set the context with firebase data
const {setUserLogin} = useContext(Context);
const { register, handleSubmit, formState: { errors } } = useForm();
const onSubmit = data => {
const auth = getAuth();
signInWithEmailAndPassword(auth, data.email, data.password)
.then((userCredential) => {
const user = userCredential.user;
setUserLogin({user});
navigate('/anuncios');
})
.catch((error) => {
let erroMessage = localizeErrorMap(error.code)
Toast('error', erroMessage);
})
};
I want to save the data in the context api and be able to take, for example, the component below and the others
import React, {useContext} from "react";
import { Context } from '../providers/auth';
export default function Index() {
const [user, setUserLogin] = useContext(Context);
//console.log(user);
return (
<h1>Logado {user}</h1>
)
}
I saw that in the browser console when I click on the component, it informs that the problem is in the line: const [user, setUserLogin] = useContext(Context);
Upvotes: 2
Views: 603
Reputation: 2642
Your context value is { userLogin, setUserLogin }
:
<Context.Provider value={{ userLogin, setUserLogin }}>
so you cannot destructure it into an array. Use const { userLogin, setUserLogin } = useContext(Context)
instead:
export default function Index() {
const { userLogin, setUserLogin } = useContext(Context);
console.log(userLogin);
...
Upvotes: 2