2

I get this error for the following code in React Native:

Invalid attempt to destructure non-iterable instance. In order to be iterable, non-array object must have a [symbol.iterator]() method

counter-context.js

import React, {useState, createContext} from 'react'

export const CounterContext = createContext();

export const CounterContextProvider = props => {
  const [count, setCount] = useState(0)

  return (
    <CounterContext.Provider value={[count, setCount]}>
      {props.children}
    </CounterContext.Provider>
  );
}

counter-display.js

import React, { useContext } from 'react';
import { View, Text, StyleSheet } from 'react-native';
import { CounterContext, CounterContextProvider } from '../context/counter-context';

export default function Counter() {
    const [count] = useContext(CounterContext);
    
    return (
        <CounterContextProvider>
            <View style={styles.sectionContainer}>
                <Text style={styles.sectionTitle}>{count}</Text>
            </View>
        </CounterContextProvider>
    )
}

const styles = StyleSheet.create({
    sectionContainer: {
        flex: 1,
        padding: 24,
    }

App.js

<SafeAreaView>
        <ScrollView
          contentInsetAdjustmentBehavior="automatic"
          style={styles.scrollView}>
          <View style={styles.body}>
            <Counter/>
          </View>
        </ScrollView>
      </SafeAreaView>

What is the reason? Seems to work in react.

1 Answer 1

1

Your useContext(CounterContext) call exists in a component that is not a descendant of <CounterContextProvider>. The <CounterContextProvider> needs to be an ancestor of <Counter>, not a descendant.

As for the error message you're getting, it's due to the array destructuring syntax in the assignment statement const [count] = useContext(CounterContext); which makes an implicit call to the return value's [Symbol.iterator]() method, if it exists. Since there is no provider in scope and the context was created without passing a default value, you're essentially evaluating const [count] = undefined;

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

Comments

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.