React - map and store search texts from cookies

0 votes
289 views
added Mar 14 in React by lcjr First Warrant Officer (11,780 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 cookies.search 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', [...(cookies.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;
  `}
>
    {cookies.search && cookies.search.map((text, index) => (
        <li key={index}>{text}</li>
    ))}
</ul>

 

1 Response

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

You'll get TypeError: cookies.search.map is not a function

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

To handle this error, you can ensure that cookies.search 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(cookies.search) && cookies.search.map((text, index) => (
  <li key={index}>{text}</li>
))}

This modification ensures that cookies.search is an array before attempting to call the map function on it. If cookies.search is not an array, the map function will not be executed, preventing the TypeError.

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