Home > Back-end >  setState is not a function in react native
setState is not a function in react native

Time:10-08

I am learning react native, have been getting this error setState is not a function in react native I searched a lot but nothing was helpful enough.

I have created this simplified code to show the issue

import React, { useState } from "react";
import { Text, View, Button } from "react-native";

const Test = ({ Test1 }) => {
  return (
    <Button
      onPress={() => {
        Test1.setState(true);
      }}
    />
  );
};

const Test1 = () => {
  const [state, setState] = useState(false);
  if (state) {
    return <Text>Test Working</Text>;
  } else {
    return <Text>Test Not Working</Text>;
  }
};

const App = () => {
  return (
    <View>
      <Test Test1={Test1} />
    </View>
  );
};

export default App;

this is the error: TypeError: Test1.setState is not a function

Please help me fix this.

CodePudding user response:

import React, { useState } from "react";
import { Text, View, Button } from "react-native";

const Test = ({ setState }) => {
  return (
    <Button
      onPress={() => {
           setState(true);
      }}
  );
};

const Test1 = ({state}) => {
 
  if (state) {
    return <Text>Test Working</Text>;
  } else {
    return <Text>Test Not Working</Text>;
  }
};

const App = () => {
    
  const [state, setState] = useState(false);
  return (
    <View>
        <Test1 state={state} />
      <Test setState={setState} />
    </View>
  );
};

export default App;

CodePudding user response:

States can be transferred to other component only as props. You need to call the Test1 component from the App and the Test component from the Test1, then you can pass the props to the Test from Test1. By this you don't need to move the state to other component. you can not pass any component as props and access state or methods from there. You can try this code:

import React, { useState } from "react";
import { Text, View, Button } from "react-native";

const Test = ({ setState}) => {
  return (
    <Button
      onPress={() => {
        setState(true);
      }}
    />
  );
};

const Test1 = () => {
  const [state, setState] = useState(false);

  if (state) {
    return <Text>Test Working</Text>;
  } else {
    return <Test setState={setState} />;
  }
};

const App = () => {
  return (
    <View>
      <Test1  />
    </View>
  );
};

export default App;

CodePudding user response:

There are two problems here.

  1. Your Test1 component is not being used at all
  2. Hooks, and local functions in general, may not be called outside of the component that they are declared on

If you want to manage some local state in your Test component, it needs to live in that component.

  • Related