Home > OS >  undefined is not an object (evaluating 'data.map')
undefined is not an object (evaluating 'data.map')

Time:09-21

const Sub_Map = () => {

const [isLoading, setLoading] = useState();
  const [data, setdata] = useState();

  useEffect(() => {
    getData();
  }, []);

  const getData = () => {
    fetch('http://. . . . /aplikasi/restapi.php?op=getJenis')
      .then(res => res.json())
      .then(json => setdata(json))
      .catch(error => alert(error))
      .finally(setLoading(false));
  };

on the "data.map" there is an error, please explain for me

  return (
    <View style={styles.container}>
      <Text style={styles.text}>Pilih Data</Text>
      <View style={styles.picker}>
        {isLoading ? (
          <ActivityIndicator />
        ) : (
          <Picker
            selectedValue={data}
            onValueChange={itemValue => setdata(itemValue)}>
            {data.map((item, key) => {
              <Picker.Item
                label={'${item.bencana}'}
                value={'${ item.id }'}
                key={key}
              />;
            })}
          </Picker>
        )}
      </View>
   );
};

please help me, i'm still newbie about react native TypeError: undefined is not an object (evaluating 'data.map')

CodePudding user response:

Write it like this, and it will work:

{data && data?.map((item, key) => { ...

CodePudding user response:

Best guess from the code snippet is that you are rendering before data is populated.

I would try something like this;

  const [hasLoaded, setHasLoaded] = useState(false);

  useEffect(() => {
    const callApi = async () => {
        await getData();
        setHasLoaded(true);
    };

    callApi();
}, []);

...

return hasLoaded ? (
<View style={styles.container}>
  <Text style={styles.text}>Pilih Data</Text>
  <View style={styles.picker}>
    {isLoading ? (
      <ActivityIndicator />
    ) : (
      <Picker
        selectedValue={data}
        onValueChange={itemValue => setdata(itemValue)}>
        {data && data?.map((item, key) => {
          <Picker.Item
            label={'${item.bencana}'}
            value={'${ item.id }'}
            key={key}
          />;
        })}
      </Picker>
    )}
  </View>
 );
};

What the above code is doing is calling your API and once it's done, it sets the hasLoaded state to true - indicating it is finished.

Then in the return, you notice I return it conditionally based on that state. So nothing will render until the API call is done.

I also amended your data mapping to allow for undefined cases.

  • Related