React does not recognize data.map as a function

Currently, I am facing an issue with a simple map function in React that is supposed to create a set amount of times.

{times.map((time) => (
          <Pill value={time} handleTimes={handleTimes} key={time} />
        ))}

The error being thrown is:

TypeError: times.map is not a function

When I check the array using console.log, it looks like this:

...
  const [times, setTimes] = useState([]);
...
  console.log("times: ",times,"keys: ",times[0])


times:  ["09:00 AM","12:00 PM","03:00 PM"] keys:  [

The function used for handling times for pills is as follows:

const handleTimes = (time, mode) => {
    let updatedTimes = times;
    if (mode === 'remove') {
      updatedTimes = times.filter((elem) => elem !== time);
    } else if (!updatedTimes.includes(time)) updatedTimes = [...times, time];
    setTimes(updatedTimes);
  };

It seems like the data coming in is being treated as a string instead of an array. How can I convert it into an array?

console.log(typeof times, times)
    string ["09:00 AM","12:00 PM","03:00 PM"]

Answer №1

During Nextjs hydration, most states are initially empty, so it is important to check for null/undefined values.

 {times?.map((time) => (
           <Pill value={time} handleTimes={handleTimes} key={time} />
         ))}

Alternatively,

{times && times.map((time) => (
          <Pill value={time} handleTimes={handleTimes} key={time} />
        ))}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Activate the Bootstrap Jquery/Ajax inline editing feature by simply clicking on the Edit button

Seeking recommendations for a way to implement inline editing. When the edit button is clicked, I want the label's content to be replaced with an input text field that can be updated in my MySQL database. This is what my code looks like: <label s ...

Send the DOM element to a processing function within AngularJS

In this code snippet, there is an attempt to pass a table cell (as a DOM object) to a function. However, it seems that the reference of 'this' does not point to the DOM object for the table cell, but rather to '$scope'. Any suggestions ...

Caching a filtered array in Redux

I am currently working with the following selectors: In my selectors.js file, I have defined the following functions: const getNodeHistory = (state) => state.session.nodeHistory; const getUnit = (state, unit) => unit; export const selectNodeHistor ...

Error in Highcharts: The property '0' is undefined and cannot be read

Attempting to integrate data from a REST API into HighCharts, but encountering an issue: TypeError: Cannot read property 'series' of undefined. This function retrieves the data from the API: $scope.myData = function(chart) { HighCharts.query ...

Configuring Next.js with Nginx in a Docker environment

I'm attempting to containerize a Next.js app with NGINX in Docker. Here is my Dockerfile for the Next.js app: FROM node:18-alpine as builder WORKDIR /my-space COPY package.json package-lock.json ./ RUN npm ci COPY . . RUN npm run build FROM node:18- ...

Generating a 3D model and integrating it with a 3D terrain display on Mapbox

My goal is to integrate a 3D model as a custom layer on Mapbox using Three.js, alongside adding a 3D terrain on the map. I have followed the documented examples for incorporating a 3D model and 3D terrain from Mapbox. The issue I'm encountering is th ...

Utilizing the power of JavaScript to specifically prevent the default behavior within an ASP server control

An ASP.NET server control is used in the code snippet below: <asp:HyperLink Visible='<%# (GetAnswer(Eval("AnsQID"))) != 1 %>' ID="HyperLink1" runat="server" NavigateUrl="#" ToolTip='Like this answer' onclick="javascript:( ...

Display column header row divider for pinned columns in v5 DataGrid

I'm attempting to customize the appearance of pinned columns in MUI's DataGrid by adding a column header-row divider. The official demo by MUI for pinned columns [https://codesandbox.io/s/qix39o?file=/demo.tsx] displays the pinned column header ...

Replace the hyperlink with plain text using JQuery

Is there a way to replace a hyperlink within an li element with different text but without removing the entire list item? <li class="pull-left"> <a href="#" class="js-close-post" data-post-id="1"> Close </a> </li> ...

It appears that the lodash throttle function is not being invoked

I recently started utilizing lodash's throttle function to control the number of calls made to an API. However, I am facing difficulties as the call doesn't seem to be triggered successfully. Below is a simplified version of what I have attempte ...

Unexpected outcomes experienced with AJAX in ASP.NET due to javascript integration

I experimented with two methods (server and client side) for initiating a JavaScript AJAX call to post a ticket on a website and then retrieve a link containing the ticket number for tracking or editing purposes. However, both approaches yielded different ...

Error during compilation in npm (symbol '_' is not recognized)

After updating all the dependencies in my JavaScript program without making any changes to my components, I encountered an error when running: npm run build The error specifically mentions a problem with one of my components: Failed to compile. ./src/c ...

How React hooks are able to access closure variables

Exploring async operations in React using hooks, I decided to create a counter example. Here is the code snippet: function App() { const [count, setCount] = useState(0); var times = count>0?"times":"time"; var txt = count + " " + times; useE ...

Tips on Guaranteeing AJAX Requests are Successfully Called in Sequential Order and Receive Responses in the Same Sequence

What is the best way to guarantee that AJAX requests are executed in a specific order and receive responses in the same order? ...

The functionality of JQuery stops functioning once ajax (Node.js, PUG) is integrated

I've been attempting to incorporate a like feature on my blog post website. When I click on the likes count, it's supposed to trigger an ajax call. In my server.js file, there's a function that handles the POST request to update the number ...

Error: VueJS mixins do not include the property definition

I've been trying to incorporate Mixins into my Vue.js code, but I've run into a few issues :/ Here's the current code for two test modules : ErrorBaseMixin.vue <script> import ErrorAlert from './ErrorAlert'; expor ...

Using jQuery to remove the td element from an HTML table

Hello everyone, I have a query. I am trying to remove a specific td from a table using JavaScript, but the remove() function is not working. Here is my code: $('.btnEliminarLicencia').off('click'); $('.btnEliminarLicencia&apo ...

The Javascript logic on the NewForm for a Sharepoint 2013 on-premise list is failing to trigger

Screen shot linkThere seems to be an issue with the code I have written. The save button should only be enabled if all 5 checkboxes are ticked, but currently, the button is not disabled on form load. I have tried adding the code in both CEWP and SEWP, bu ...

Is ReactJS known for its exceptional performance in rendering large matrices?

Although I have no prior experience with ReactJS, I've heard about a great feature it offers called virtual DOM. It reminds me of the concept of virtual elements in Silverlight where invisible elements are removed from the tree to enhance user-perceiv ...

Guide to importing multiple controllers using express

For my upcoming full stack project, I am working on various controllers like signup, login, and profile. Instead of manually requiring each controller and adding them to the app using individual lines of code, I am seeking a more efficient solution. I env ...