Issue
LOG [TypeError: Invalid attempt to destructure non-iterable instance. In order to be iterable, non-array objects must have a Symbol.iterator method.]
With my UserContext :
import React, { useContext, useEffect, useLayoutEffect, useState } from "react";
import { useNavigation } from "@react-navigation/native";
import { Ionicons } from '@expo/vector-icons';
import { UserType } from "../UserContext";
const [userId, setUserId] = useContext(UserType);
const token = await AsyncStorage.getItem("authToken");
const decodedToken = jwt_decode(token);
const userId = decodedToken.userId;
console.log(userId);
setUserId(userId);
this is my UserContext.js
import { createContext, useState } from 'react';
const UserType = createContext();
const UserContext = ({ children }) => {
const { userId, setUserId } = useState("");
return (
<UserType.Provider value={{ userId, setUserId }}>
{children}
</UserType.Provider>
)
}
export {UserType, UserContext}
My App.js
import { StatusBar } from 'expo-status-bar';
import { StyleSheet, Text, View } from 'react-native';
import StackNavigator from './StackNavigator'
import { UserContext } from './UserContext';
export default function App() {
return (
<>
<UserContext>
<StackNavigator/>
</UserContext>
</>
);
}
please if someone can help me
i have tried to change
const [userId, setUserId] = useContext(UserType);
with
const {userId, setUserId} = useContext(UserType);
but it give me this error
TypeError: setUserId is not a function (it is undefined)
Solution
Here, you used this useContext
in the wrong way. Whatever you pass through the provider, you will get that same object as a response through the useContext
.
So here, you useContext
hook will be (Doc For Help)
const { userId, setUserId } = useContext(UserType);
But you will get an error as setUserId is not a function but undefined
. Because you made another mistake inside the UserContext.js file. You have written the useState
hook as (Doc For Help)
const { userId, setUserId } = useState("");
but useState
always returns an array of two values like - [value, setValue]
, not an object. So, it should be
const [ userId, setUserId ] = useState("");
I think it will solve your issue. I have also shared the related docs link for better understanding.
Answered By - Souvik Ghosh
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.