Murat Kızılöz
Murat Kızılöz

Reputation: 95

React native _this.state.data.map is not a function

In console, I can get this.state.data in render. Everything looks normal. But I get this.state.data.map is not a function error. What am I doing wrong? I would be very happy if there is someone who can help. Thanks in advance

export default class ProfileScreen extends Component {

constructor(props) {
    super(props);
    this.state = {
        data: [],
        hash: '',
    };
}

_retrieveData = async () => {
    try {
        const value = await AsyncStorage.getItem('token');
        console.log(value);
        this.setState({
            hash: value,
        });
    } catch (error) {
        // Error retrieving data
    }
};

getInfo = async () => {
    try {
        const response = await axios.get('http://yakakartim.net/museb/kollektif/loginInfo?hash=' + this.state.hash);
        this.setState({
            data: response.data.message
        })
    } catch (e) {
        console.log(e)
    }
};

componentDidMount() {
    this._retrieveData();
    this.getInfo()
}

list = () => {
    return this.state.data.map(info => {
        return (
            <View style={{ margin: 10 }}>
                <Text>{info.email}</Text>
            </View>
        );
    });
};

render() {
    console.log('render',this.state.data)
    console.log('render',this.state.hash)
    return <View>{this.list()}</View>;
}

}

Upvotes: 0

Views: 47

Answers (2)

Murat Kızıl&#246;z
Murat Kızıl&#246;z

Reputation: 95

thanks, the incoming data is not an array. I found the solution like this.

this.setState({
   data: [response.data.message]
})

Upvotes: 0

Ali Hayder
Ali Hayder

Reputation: 325

This is because you are updating the data variable which is initially an array in state but later in getInfo function you have update it like this

 this.setState({
        data: response.data.message
    })

I dont know what is in "message". But if it is not an array, then map function will not work with "data" as it only works with variables which are iterate-able. I mean which are of array data type.

Upvotes: 1

Related Questions