React - loop for cookie in reverse order with minimize and see all links

0 votes
18 views
added Feb 2 in React by lcjr First Warrant Officer (10,930 points)
import React, { useState } from 'react';
import { useCookies } from 'react-cookie';

const SidebarHistory = () => {
  const [cookies, setCookie] = useCookies(['searchHistory']);
  let searchHistory = cookies.searchHistory || [];

  // Reverse the array to show the latest item on top
  searchHistory = searchHistory.reverse();

  // State to track whether to show all history or limit to 8 items
  const [showAllHistory, setShowAllHistory] = useState(false);

  // Displayed history based on the state
  const displayedHistory = showAllHistory ? searchHistory.slice().reverse() : searchHistory.slice(0, 8);

  const handleDelete = (index) => {
    const updatedHistory = [...searchHistory];
    updatedHistory.splice(index, 1);
    setCookie('searchHistory', updatedHistory.reverse(), { path: '/' });
  };

  return (
    <div className='sidebar_history'>
      <ul>
        {displayedHistory.map((entry, index) => (
          <li key={index} className='history-item'>
            {entry}
            <div className='history-overlay'>
              <a href='#'>Edit</a>
              <a href='#' onClick={() => handleDelete(index)}>Delete</a>
              <a href='#'>Share</a>
            </div>
          </li>
        ))}
      </ul>
      <div>
        {searchHistory.length > 8 && (
          <a href='#' onClick={() => setShowAllHistory(!showAllHistory)}>
            {showAllHistory ? 'Minimize History' : 'See All History'}
          </a>
        )}
      </div>
    </div>
  );
};

export default SidebarHistory;

 

lazacode.org - Malaysia's programming knowledge sharing platform, where everyone can share their finding as reference to others.
...