1

My app is trying to make an API call and display the data from it in a modal. It isn't working because I'm storing the response from the API call as an array at the moment, meaning I can't access the sub-elements of the response.

My question, then: is there some way to either:

  • Store an object using State so that I can conveniently reference parts of that object?

OR

  • Parse an array as a JSON so I can take the data from the response and process it as a JSON when needed?

I realise this is kind of a weird question, so any answer that would achieve the same result would also be great.

Here's my code:

const DrinkPopup = (props) => {

  let [drinkDetails,setDrinkDetails] = useState([])
  let selectedDrinkId = props.drink

  const getDrinkAsync = async (selectedDrinkId) => {
    try {
      let response = await fetch('https://www.thecocktaildb.com/api/json/v1/1/lookup.php?i='+selectedDrinkId);
      let data = await response.json();
      setDrinkDetails(data.drinks)
      return true;
    } catch (error) {
      console.error(error);
    }
  }

  useEffect (() =>  { 
    getDrinkAsync(selectedDrinkId)
    console.log(selectedDrinkId) 
    console.log(drinkDetails) 
  },[]);
  


  return(
    <Modal isVisible={props.modalVisible}
    onBackdropPress={()=>{props.setModalVisible(false)}} //allows closing modal by tapping outside it or back button
    onBackButtonPress={()=>{props.setModalVisible(false)}} 
    animationIn={"slideInUp"}>  
      <View style={styles.infocard}>
          <View style={styles.titleBox}>
            <Text style={styles.header}>{drinkDetails.idDrink}</Text>
          </View>
      </View>
    </Modal>


  )


}
Swystem
  • 35
  • 8
  • 2
    You need to consider: do I have control over the response from the server side? If the answer is: no, then you need to deal with converting the array into an object yourself in a function typically known as a data transform. You have to define how you want your object to look for your application, we cannot imagine that for you. Otherwise look at [this example](https://stackoverflow.com/questions/4215737/convert-array-to-object) – AGE Jan 13 '21 at 19:41

1 Answers1

0

A really easy way to convert your array to an object is to use Object.assign like so:

Object.assign({}, data.drinks)

It would return an object with numbered keys and you can store that to state.

CoderLean
  • 232
  • 1
  • 6
  • Sorry, I'm pretty new to React Native - how do I store an unnamed object to state? – Swystem Jan 14 '21 at 10:01
  • Use a useState hook if it's local state for that component only or use ContextAPI/Redux to make it available to other components in your app – CoderLean Jan 14 '21 at 11:26