Can't set state in js react-native

Getting error while trying to setState in React Native.

Code

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

const UselessTextInput = () => {
  state = { currentDate: "" };

  const setCurentDate = (val) => {
    this.setState({currentDate : val});
  };

  const [value, onChangeText] = React.useState("");

  return (
    <View>
      <Text
        style={{
          alignSelf: "center",
          marginTop: 60,
          fontWeight: "bold",
          fontSize: "25",
        }}
      >
        BirthReminder
      </Text>
      <Text style={{ alignSelf: "center", marginTop: 15, fontSize: 15 }}>
        Enter your friend's birthdate, please
      </Text>
      <TextInput
        clearTextOnFocus={true}
        style={{
          height: 40,
          borderColor: "gray",
          borderWidth: 1,
          marginTop: 20,
          width: 250,
          alignSelf: "center",
        }}
        onChangeText={(value) => setCurentDate(value)}
        value={value}
      />
      <Button title="Add to list"></Button>
    </View>
  );
};

export default UselessTextInput;

Error

TypeError: undefined is not an object (evaluating ‘_this.setState’)

35 thoughts on “Can't set state in js react-native”

  1. I think you got a bit mixed up

    replace this as this is the syntax if you use Class component

      state = { currentDate: "" };
      const setCurentDate = (val) => {
        this.setState({currentDate : val});
      };
    

    with:

      const [date, setDate] = React.useState();
      const setCurentDate = (val) => {
        setDate(val);
      };
    

    and have a look at the documentation

    Reply
  2. this.setState isn’t allowed in functional component. Try to use React.useState for currentDate

    const [currentDate, setCurrentDate] = React.useState("");
    
    ...
    
    const setCurentDate = (val) => {
        setCurrentDate(val);
    };
    
    Reply
  3. useState Hook

    Functional components don’t have access to setState method but useState hook.

    useState hook works by defining the name of value, e.g. foo followed by it’s setter. It’s a convention to name the setter with the same name as that of value with set prefix, i.e. setFoo

    const [foo, setFoo] = useState('hi');
    // pass the initial value here -^^-
    

    Solution

    import { useState } from 'react';
    import { TextInput } from 'react-native';
    
    const Component = () => {
      const [value, setValue] = useState('');
    
      return <TextInput value={value} onChangeText={setValue} />;
    };
    
    
    Reply

Leave a Comment