Advertisement
Guest User

Untitled

a guest
Apr 4th, 2020
305
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // The parent component to this is a page, it loads data client side from my API and passes that data to this component as a prop.
  2. // rowData (state) is not being populated by data (prop), even though I can see the correct data in the console log of the 2nd render
  3. // The 1st render console log shows data as an empty array, and rowData as an empty array
  4. // The 2nd render console logs the correct contents in the data array, rowData is still an empty array
  5. // table does not get updated
  6.  
  7. //I can solve this using useEffect and setting the rowData, but I dont think I should have to, unless NextJS is forcing me to.
  8.  
  9. import React, { useState } from "react";
  10. import { sortBy } from "../../utils/sortBy";
  11.  
  12. export default function Table({data}) {
  13.   const [ rowData, setRowData ] = useState(data); // I think this is the issue due to SSR w/ NextJS
  14.  
  15.   function clickSort(key) {
  16.     setData([...rowData].sort(sortBy(key))); // this works, can ignore
  17.   }
  18.  
  19.   const table = rowData.map((row, index) => {
  20.     return <div key={index}>{row.name}</div>; // this works, can ignore
  21.   });
  22.  
  23.   console.log(data);
  24.   console.log(rowData);
  25.   return (
  26.     <div>
  27.       <button onClick={() => clickSort("name")}>Click to sort by Name</button>
  28.       <button onClick={() => clickSort("id")}>Click to sort by ID</button>
  29.       {table}
  30.     </div>
  31.   );
  32. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement