Search code examples
javascriptreactjsreact-nativenative

TypeError: undefined is not an object (evaluating 'items.map')


After receiving items, the following error occurs. At the moment I'm just learning and have looked at other answers on this topic, nothing comes up.

export default function App() {
  const [items, setItems] = React.useState();

  React.useEffect(() => {
    axios
      .get('https://62fa26ddffd7197707e66da8.mockapi.io/items')
      .then(({ data }) => {
        setItems(data);
      })
      .catch((err) => {
        console.log(err);
        Alert.alert('Ошибка', 'Ошибка при получении статей');
      });
  }, []);

  return (
    <View>
      <StatusBar style="inverted" />
      {items.map((obj) => (
        <Post title={obj.title} price={obj.price} imageUrl={obj.imageUrl} />
      ))}
    </View>
  );
}

Error:

 ERROR  TypeError: undefined is not an object (evaluating 'items.map')

This error is located at:
    in App (created by ExpoRoot)
    in ExpoRoot
    in RCTView (created by View)
    in View (created by AppContainer)
    in RCTView (created by View)
    in View (created by AppContainer)
    in AppContainer
    in main(RootComponent)

Solution

  • items default value is not an array, you just need to set blank array as default.

    const [items, setItems] = React.useState([]);