React - map and store search texts from cookies

0 votes
added Mar 14 in React by lcjr First Warrant Officer (11,970 points)

To display all stored search texts from cookies in the .cookie_store, you need to map through the array of search texts stored in and render each one as a list item. Here's how you can modify your code to achieve this:

useState hook

const [cookies, setCookie] = useCookies(['search']);


inside the button 

const handleSearch = () => {
  // Store search as cookie
    setCookie('search', [...( || []), searchText], { path: '/', maxAge: 604800 }); // Store for 7 days


Use in JSX

<ul css={css`
    clear: both;
    padding: 20px 0;
    position: relative;
    z-index: 100;
    { &&, index) => (
        <li key={index}>{text}</li>


1 Response

0 votes
responded Mar 14 by lcjr First Warrant Officer (11,970 points)

You'll get TypeError: is not a function

There'll likely an issue with accessing the search property of the cookies object. The error suggests that is not an array, hence you cannot call the map function on it.

To handle this error, you can ensure that is properly initialized as an array before attempting to map over it. Here's how you can modify the code to handle this:

{Array.isArray( &&, index) => (
  <li key={index}>{text}</li>

This modification ensures that is an array before attempting to call the map function on it. If is not an array, the map function will not be executed, preventing the TypeError. - Malaysia's programming knowledge sharing platform, where everyone can share their finding as reference to others.