6

I'm new to react. I've read through react documentation. I've no idea why it is not working. So, I come up here.

I'm trying to create pagination in react. Below is my table component.

const Table = (props) => {
  const { description, itemCount, tableHeaders, items } = props;

  const pageSize = 5;
  const [currentPage, setCurrentPage] = useState(1);

  function handlePageChange(page) {
    setCurrentPage(page);
  }

  const registerations = paginate(items, currentPage, pageSize);
  // HERE: registerations data is correct and then I pass it to TableBody component.

  return (
    <React.Fragment>
      <TableDescription description={description} count={itemCount} />
      <div className="bg-white block w-full md:table">
        <TableHeader items={tableHeaders} />
        <TableBody items={registerations} />
      </div>
      {/* Footer & Pagination */}
      <div className="bg-white block flex px-6 py-4 justify-between rounded-bl-lg rounded-br-lg">
        <div className="sm:flex-1 sm:flex sm:items-center sm:justify-between">
          <Pagination
            itemsCount={items.length}
            pageSize={pageSize}
            currentPage={currentPage}
            onPageChange={handlePageChange}
          />
        </div>
      </div>
      {/* end Footer & Pagination */}
    </React.Fragment>
  );

and that registerations array is received by TableBody component. The problem here in TableBody component is that I can't set props value to state using useState hook.

const { items: passedItems } = props;
console.log(passedItems); // ok -> I got what I passed.

const [items, setItems] = useState(passedItems);
console.log(items); // not ok -> items is previously passed items.

How can I make it right? Thank You.

Htet Phyo Naing
  • 464
  • 7
  • 20
  • 1
    Why do you need to keep them in the state? This is how state's supposed to behave - not reinitialize on every render – Łukasz Karczewski Jun 06 '20 at 15:52
  • Because I need to keep track of which registerations has opened view-more btn. In my UI, I have view more button on every registeration. So, if I click one of those buttons, I've set { popupVisivility = true } into that registeration object using setItems(). And then table is re-rendered and popup is shown. Is there another way around or other right way to get that achievement? – Htet Phyo Naing Jun 06 '20 at 16:11

3 Answers3

4

I you want this to work in it's current form:

const { items: passedItems } = props;
console.log(passedItems); // ok -> I got what I passed.

const [items, setItems] = useState([]);
console.log(items); // not ok -> items is previously passed items.
useEffect(() => {
  setItems(passedItems)
}, [passedItems])
Łukasz Karczewski
  • 1,084
  • 8
  • 12
3

While use useState hooks you should understand why we need useEffect, so in class based components you had the privilege to use callback function in this.setState which will give you the current updated value

this.setState(() => {
  name: 'john'
}, () => console.log(this.state.name)) // you will get the immediate updated value

So when you come to functional component

const [name, setName] = useState(props.name)
console.log(name) // won't get the updated value

for to get the updated value you can use React.useEffect hook which will trigger whenever array deps as the second argument got changed.

useEffect(() => {
 // logic based on the new value
}, [name]) // so whenever the name value changes it will update and call this useEffect

the useEffect can be called in three ways

First One

Without passing an array of deps

useEffect(() => {}) // this will call everytime

Second One

Passing empty array

 useEffect(() => {}, []) // passing empty array,it will call one time like the componentDidMount of class based component

Third One

Passing array deps (dependencies)

 useEffect(() => {

} , [name, count]) // whenever there is an update of name and count value it will call this useEffect

So in your case you can do the below way

useEffect(() => {
  setItems(passedItems)
}, [passedItems]) // whenever passedItems changes this will call and setItems will set the new passedItems

I hope you have clear idea on this.

Learner
  • 8,379
  • 7
  • 44
  • 82
1

You need to add a useEffect to update state when the props change.

From the useState docs:

During subsequent re-renders, the first value returned by useState will always be the most recent state after applying updates.

const TableBody = (props) => {
   const { items: passedItems } = props;

   // items is set to `passedItems` only on first render
   // subsequent renders will still retain the initial value in state
   // until `setItems` is called
   const [items, setItems] = useState(passedItems);
   
   // add a `useEffect` to update the state when props change
   useEffect(() => {
     setItems(items)
   }, [items])

   // 
}
HoldOffHunger
  • 18,769
  • 10
  • 104
  • 133
iamaatoh
  • 758
  • 5
  • 12