Home > Software design >  React custom control return values
React custom control return values

Time:09-23

I have following state variables

const [college,setCollege]=useState({})

When a data is fetched from DB, I am using following statement to set the college object

function fetchData()   {setCollege(data)}

"college" object has array of "students"

I am using a map statement to iterate through the "students" as follows

college.students.map((std,i)=>
    {
      <tr> <td>std.name </td>
      </tr>
 }

My problem is : First time (say college "a" has 30 students), everything works great

But when next time, data is fetch for another college say "b" which has 10 students, still the Map function uses old "student" object which has 30 students and the code fails

In actual, when I fetch new college details, inner student object also needs to get updated but its not working during map.

Could you please help....

CodePudding user response:

You could try to create a new object when your data is received, this way it will rerender the component:

function fetchData()   {setCollege({...data})}
  • Related