yemy
yemy

Reputation: 838

React, Getting TypeError: Invalid attempt to destructure non-iterable instance when using global state with Context

I try to use context for accessing state globally but get the following error:

TypeError: Invalid attempt to destructure non-iterable instance.
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.

I tried to solve the problem with adapting the use of context from this Stack Overflow Question.

File from which I wanna get state from:

const test = () => {
  const [selectedValueRound, setSelectedValueRound] = useState("10 rounds");
  return (
    <View>
      <RoundContext.Provider
        value={[selectedValueRound, setSelectedValueRound]}
      >
        <View>
          <Picker
            selectedValue={selectedValueRound}
            onValueChange={(itemValue, itemIndex) =>
              setSelectedValueRound(itemValue)
            }
          >
            <Picker.Item label="1 round" value="0"></Picker.Item>
            <Picker.Item label="2 rounds" value="1"></Picker.Item>
          </Picker>
        </View>
      </RoundContext.Provider>
    </View>
  );
};

File for context:

export const RoundContext = createContext(false);

File where I try to call context and error appears:

const SomeFile = () => {
  const [selectedValueRound, setSelectedValueRound] = useContext(RoundContext);

  return (
    <View>
      <Text>{selectedValueRound}</Text>
    </View>
  );
};
export default SomeFile;

Upvotes: 1

Views: 2667

Answers (1)

Youssouf Oumar
Youssouf Oumar

Reputation: 45903

Make sure you wrap SomeFile inside RoundContext.Provider, as for now, it seems like you are not. Only wrapped components inside the Provider can consume a context.

Also, make sure that every React component starts with a capital letter, Test instead of test. Like this:

const Test = () => {
  const [selectedValueRound, setSelectedValueRound] = useState("10 rounds");
  return (
    <View>
      <RoundContext.Provider
        value={[selectedValueRound, setSelectedValueRound]}
      >
        <View>
          <Picker
            selectedValue={selectedValueRound}
            onValueChange={(itemValue, itemIndex) =>
              setSelectedValueRound(itemValue)
            }
          >
            <Picker.Item label="1 round" value="0"></Picker.Item>
            <Picker.Item label="2 rounds" value="1"></Picker.Item>
          </Picker>
        </View>
        <SomeFile/>
      </RoundContext.Provider>
    </View>
  );
};

Upvotes: 2

Related Questions