Home > Mobile >  How to hide a particular data initially while calling Axios api in map function in react native
How to hide a particular data initially while calling Axios api in map function in react native

Time:01-23

I want that the data at the index 1 and 2 are hiding and all data are show on the screen except these two data. I am using the map function for show data on the screen and my data is coming from api call. Here is my code:

const [show, setShow] = useState(true);
axios
  .get('url', {
    headers: {
      'Content-Type': 'application/json',
      Authorization: `Bearer token-key`,
    },
  })
  .then(response => {
    console.log('response', response);
    const data = response.data;
    setData(data);
    console.log('data=\>', data);
    showItem();
  })
  .catch(error => {
    console.log('error', error.response);
  });

const showItem = () => {
  data.map((item, index) => {
    console.log('index of show item', index);
    if (index == 1 || index == 2) {
      const show = false;
      setShow(show);
    } else {
      const show = true;
      setShow(show);
    }
  });
};

**My logic does not work and the data at index 1 and 2 are not hiding during api call. here is my ui part: **

<View style={styles.leftSideView}>
  {data && data.map((item, index) => { return (
  <TouchableOpacity key={item.id} style={styles.leftViewStyle}>
    {show == true ? (
    <Text style={styles.leftView}>{item.name.en}</Text> ) : null}
  </TouchableOpacity>
  ); })}
</View>

CodePudding user response:

const [show, setShow] = useState(false);
const [data, setData] = useState([]);

useEffect(()=>{
axios
  .get('url', {
    headers: {
      'Content-Type': 'application/json',
      Authorization: `Bearer token-key`,
    },
  })
  .then(response => {
    const data = response.data;
    setData(data);
  })
  .catch(error => {
    console.log('error', error.response);
  });

},[])

if you want to show all the data you just have to setShow(true)

<View style={styles.leftSideView}>
  {data.map((item, index) => { 
  return (
  <TouchableOpacity key={item.id} style={styles.leftViewStyle}>
    { (!show && (index == 1 || index == 2) ) ? '' : <Text style={styles.leftView}>{item.name.en}</Text> }
  </TouchableOpacity>
  ); }) 
}
</View>

CodePudding user response:

In your showItem(), you are mapping through data but you are setting true when you are in the last item which makes show always true (since it is not index 1 or 2). Instead, you can remove it and change your UI part like this:

<View style={styles.leftSideView}>
  {data && data.map((item, index) => { return (
  <TouchableOpacity key={item.id} style={styles.leftViewStyle}>
    {index != 1 || index != 2 && (
    <Text style={styles.leftView}>{item.name.en}</Text> )}
  </TouchableOpacity>
  ); })}
</View>
  • Related