-2

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)

2 Answers2

1

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

const [items, setItems] = React.useState([]);
Ravi
  • 34,851
  • 21
  • 122
  • 183
0

Don't forget that first render will be with your default state in useState. So you need write a condition or pass valid default value in useState like empty array

Rusty Nail
  • 120
  • 1
  • 7