Home > Net >  React, Getting TypeError: Invalid attempt to destructure non-iterable instance when using global sta
React, Getting TypeError: Invalid attempt to destructure non-iterable instance when using global sta

Time:05-20

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;

CodePudding user response:

In order for this to work, make sure you wrap SomeFile inside RoundContext.Provider, as for now it seems that you are not doing so.

Only wrapped components inside the provider can consume the context.

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

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>
  );
};
  • Related