2

I have following component where I want to display data from an API, ShopScreen.js. I retrieve data with useEffect hook from API in service folder, and everything is ok, the json data is being loaded into data variable from useState hook, when I console.log it. I have problem to the display data from this variable with map method. I get the error: Cannot read property 'map' of undefined. Can spot somebody where the problem is? ShopScreen.js:

import React, { useState, useEffect } from 'react';
import { View, Text, StyleSheet, Button } from 'react-native';
import { fetchShops } from '../services/fetchShops';

const ShopsScreen = props => {
    const [data, setShops] = useState({});

    useEffect(() => {
        fetchShops()
            .then(response => response.json())
            .then(data => setShops(data));
    }, []);

    return(
        <View>
            <Text>The Shops Screen!</Text>
                {data.result.map(shop => {return (<Text>{shop.address}</Text>)})}
        </View>
    );
};

export default ShopsScreen;

My service for fetching data is fetchShops.js

export const fetchShops = () => {
    const URL = `https://vilvumbiyl.execute-api.eu-west-1.amazonaws.com/Dev/store/MEBD/list`;
    return fetch(URL)
}
4
  • 2
    Try something like this {data.result && data.result.map(shop => {return (<Text>{shop.address}</Text>)})} Commented Apr 17, 2020 at 19:05
  • Sajeeb Ahamed what means this? Commented Apr 17, 2020 at 19:08
  • 1
    Check it the data.result is available or not before using map. Commented Apr 17, 2020 at 19:09
  • Aha because of asynchronous call. I first time see this syntax. Thanks. Commented Apr 17, 2020 at 19:12

2 Answers 2

1

useEffect without any params is equal to componentDidMount and for this reason, is called after the render.

So, the first time your jsx code is called, data.result.map is undefined and only after the re-render, do to the response of fetchShops(), it has a value.

You simply need to check the value like this:

data.result && data.result.map()

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

Comments

1

You can try:

const [data, setShops] = useState({result : {}});

or test data.result before use map on it.

ShopsScreen returns your view(JSX) before you get answer from your rest API. The result is null. You get the exception.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.