-5

so I have a response from an API like this, How do I check the empty object from the API inverse? I have tried using lodash to check it but this did not work well in react native, I have not studied it further

this is my state

const [product, setProduct] = useState([])
const [loading, setLoading] = useState(true)

  const getProduct = () => {
    api.get(`/v1/snack/product/nearby?idKecamatan=${dataKecamatan.idKecamatan}`,
      { headers: { 'Authorization': 'Bearer' + AsyncStorage.getItem('app-token') } }
    )
      .then(res => {
        setProduct(res.data)
        setLoading(!loading)
        console.log(res.data)
      })
  }

  useEffect(() => {
    navigation.addListener('focus', () => {
      getProduct()
    })
  }, [navigation])

<View>
  {Object.keys(product.Data).length === 0 ? (
    <Text>data from 'Data' is empty</Text>
     ) : (
    <View>
      <Text>Data not empty</Text>
    </View>
  )}
</View>

if Data is not empty

{
    "Data": {
        "data": [
            {
                "idSnack": 1,
                "codeSnack": "MCA69825829",
                "nameSnack": "Taro",
                "imageSnack": "localhost/snack-upload/public/media/product/130720xMDVDa_8hrNIx.jpg",
                "price": "16500.00",
                "rating": 0,
                "productSold": 0,
                "favStatus": 1,
                "idAgen": 2
            }
        ],
        "metadata": {
            "total": 2,
            "count": 2,
            "per_page": 20,
            "current_page": 1,
            "total_pages": 1,
            "prev_page": "",
            "next_page": ""
        }
    },
    "Message": "SUCCESS"
}

if the data is blank the response is like this:

{
    "Data": {},
    "Message": "Tidak ada snack disekitarmu"
}

I want if data is empty to return like this

<View>
  {Object.keys(product.Data).length === 0 ? (
    <Text>gk ada</Text>
     ) : (
    <View>
      <Text>ada</Text>
    </View>
  )}
</View>

1 Answers1

0

You check if Data.data exists -->

if (Data.data) {
  // show data
} else {
  // handle null response
}

Alternatively, you can check the length of Data keys: Object.keys(Data).length

Ritu
  • 66
  • 6