-1

I am working on Reactjs and using nextjs,I am fetching data using axios, I just want to check before map/loop that whether whether array is empty or not , means if code/loop should work if i have data in array (students.data),How can i do this ? Here is my current code

const [students,setStudents] = useState({
  data: '',
  loading: true
})
const [name,setName] = useState('');
const handleClick2 = async() => {
    $("#mostviews").hide();
        const response = await axios.get(`https://xxxxxxxxxxxxxx.com/${spath}`)
     setStudents({
        data: response.data,
        loading: false
    })
}

{students.data.map((caseStudy ) => (
<a>{caseStudy.title}</a>
))}

In Network tab i am getting data like following way

0   Object { id: "66", cat_name: "pined", title: "Game Engine", … }
1   Object { id: "40", cat_name: "pined", title: "Alpha Release Time !", … }

3 Answers3

0
 {students && students.length ?
     students.data.map((caseStudy) => (
      <a>{caseStudy.title}</a>
  )) : ""}
0

The best way for your requirement and your current code is to use && operator. Check the following.

 {students.data?.length > 0 &&
     students.data.map((caseStudy) => (
      <a>{caseStudy.title}</a>
  ))}
Myat Thiha
  • 273
  • 2
  • 8
0

You need to modify your code like this, you are using wrong brackets () instead of {}, and if there only one line you can just skip it by writing it in single line as we do in arrow functions usually:

const [students,setStudents] = useState({
  data: [], //change string to array
  loading: true
})
const [name,setName] = useState('');
const handleClick2 = async() => {
    let arr = []
    $("#mostviews").hide();
        const response = await axios.get(`https://xxxxxxxxxxxxxx.com/${spath}`)
        for (const key in response.data) { //if assuming you are getting objects in object instead of obj in array
            arr.push(response.data[key])
        }
     setStudents({
        data: arr,
        loading: false
    })
}

{students.length > 0 && students.data.map((caseStudy ) => {
    return <a>{caseStudy.title}</a>
})}

or if you want to render something when there is no data in array then use:
condition ? renderThis : OrThis

PakDragoon
  • 149
  • 2
  • 11