0

I am following this video tutorial on Redux. I followed the code exactly as the person from the tutorial but when the app renders I get an error saying -

TypeError: undefined is not an object (evaluating 'this.state'

Here's the error stack:

enter image description here

And here's the code that I use for the component:

import React from 'react'
import {View, Text, StyleSheet, TextInput, TouchableOpacity} from 'react-native'
import {Ionicons} from '@expo/vector-icons'
import {connect} from 'react-redux' // used to connect the Store with this component

function AddTodo() {

    state = {
        text: ''
    }

    addTodo = (text) => {
        this.props.dispatch({type:'ADD_TODO', text})
        this.setState({text: ''})
    }

    return (
        <View style={{flexDirection: 'row', marginHorizontal: 20}}>
            <TextInput 
                onChangeText={ (text) => this.setState({text})}
                value={this.state.text}
                placeholder="Eg. Create new Video"
                style={{borderWidth: 1, borderColor:'#eaeaea',
                        backgroudColor:'#f2f2e1', height: 50, flex:1, padding: 5}} />
            
            <TouchableOpacity onPress={() => this.addTodo(this.state.text)}>
                <View style={{height:50, backgroundColor:'#f2f2e1', alignItems:'center', justifyContent:'center'}}>
                    <Ionicons name="md-add" size={30} style={{color:'#de9595', padding:10}}/>
                </View>
            </TouchableOpacity>
        </View>
    )
}

export default connect()(AddTodo) //This is how we connect the Store with the component

const styles = StyleSheet.create({
    container:{
        flex:1,
        alignItems:'center',
        justifyContent:'center'
    }
})

Why am I getting this error?

1 Answer 1

2

You can only use this in a class, referring to the instance of that class. In your functional components you cannot have a persistent state without using the hook useState.

Do this instead:

const [state, setState] = useState({text: ''});

And access use your state like so: state.text.

Always call your hooks at the top level, before conditionals and renders.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.