How I Implemented local storage and a simple Pagination to my Alt school counter App

How I Implemented local storage and a simple Pagination to my Alt school counter App

·

2 min read

During my second-semester alt school exam, i worked on building custom hooks with useReducer to test the custom hook I built i used a basic counter app for testing and everything worked fine my use counter App could return Value, increment, and decrement, reset just by calling the useCounter() and passing an initial value. I decided to upgrade the app by adding a save button, storing the saved details to the local storage so on page refresh the total counts are not lost and also adding pagination

To achieve this all I did was add this block of code to my initial react app.

  const [data,setData]=useState('')

  useEffect(() => {
    const data = JSON.parse(localStorage.getItem('data'));
    if (data) {
     setData(data);
    }
  }, []);

  useEffect(() => {
    localStorage.setItem('data', JSON.stringify(data));
  }, [data]);

The first line sets data to an empty string
The second line calls the useEffect hook on page load and gets the data stored in the local storage if there is any data if not data value is still empty

The second useEffect sets the data in our local storage whenever there are changes to the data state. I am making changes to the data with every click of the save button and the code below is what happens to data whenever the save button is clicked

  const handleSave=()=>{
    const newInfo={
      id:uuidv4(),
      total:value,
      time:new Date().toLocaleString().replace(',','')
    }

        setData([newInfo,...data])
  }

I used uuId an npm package to generate unique ids when I'm looping through the data array.

Lastly for the Pagination here is the code I used in achieving it

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

  const indexOflastPost=currentPage* postPerPage;
  const indexOfFirstPost=indexOflastPost -postPerPage
  const currentPost= data.slice(indexOfFirstPost,indexOflastPost)
  const handleDouble = () => {
    setvalue(value*2);
  };
  const handleNext=()=>{

     setCurrentPage(currentPage+1)

  }
  const handlePrev=()=>{

  if(currentPage>1){
    setCurrentPage(currentPage-1)
  }

The code above allows for only five list items on the page whenever it passes 5 items a new page is created and can be asses with the next button.

This is what the final app looks like now

To see the source code you can check my git hub repo Here
Happy coding ✌...