learner-materials-api-calls-and-hooks-in-react

Activity 3 - Character pagination

Character pagination

You might have noticed the Next and Previous buttons. Try giving them a click.

Notice that the page number changes but it doesnโ€™t update the list of characters.

๐Ÿ™‹๐Ÿป Which component includes the Prev Page and Next Page buttons?

Click here to see the answer
Navigation component

๐Ÿ™‹๐Ÿป How does the Next button update the state of the currentPage variable?

Click here to see the answer
You pass the setCurrentPage function down as a prop into the component.

The setCurrentPage function is provided by the useState hook and allows us to update the state of the currentPage variable.

We could say that a โ€œside effectโ€ of changing the currentPage variable would be getting another page of character data.

๐Ÿ™‹๐Ÿฝโ€โ™€๏ธ What hook might we use to implement a side effect action?

Click here to see the answer
The useEffect hook

Utilising useEffect

๐Ÿ‘‰ We can use the useEffect hook again to attach an action to the currentPage changing. Update your useEffect defintion, letโ€™s remove that hard coding of the pageNumber being 1 and utilise the currentPage variable.

useEffect(() => {
  getCharacters(currentPage);
}, [currentPage]);

Also notice below that we put the currentPage variable as a value in the array of dependencies. This tells the hook that our side effect should run every time the currentPage variable changes.

๐Ÿ‘‰ Try your pagination now, do the characters change when you click Next or Previous? If they do go ahead and commit/push your changes up. Weโ€™re making great progress!!

Now lets move on to activity 4 and enable the favouriting of characters