React JS - Uncaught TypeError: this.props.data.map is not a function
The .map
function is only available on array.
It looks like data
isn't in the format you are expecting it to be (it is {} but you are expecting []).
this.setState({data: data});
should be
this.setState({data: data.conversations});
Check what type "data" is being set to, and make sure that it is an array.
Modified code with a few recommendations (propType validation and clearInterval):
var converter = new Showdown.converter();
var Conversation = React.createClass({
render: function() {
var rawMarkup = converter.makeHtml(this.props.children.toString());
return (
<div className="conversation panel panel-default">
<div className="panel-heading">
<h3 className="panel-title">
{this.props.id}
{this.props.last_message_snippet}
{this.props.other_user_id}
</h3>
</div>
<div className="panel-body">
<span dangerouslySetInnerHTML={{__html: rawMarkup}} />
</div>
</div>
);
}
});
var ConversationList = React.createClass({
// Make sure this.props.data is an array
propTypes: {
data: React.PropTypes.array.isRequired
},
render: function() {
window.foo = this.props.data;
var conversationNodes = this.props.data.map(function(conversation, index) {
return (
<Conversation id={conversation.id} key={index}>
last_message_snippet={conversation.last_message_snippet}
other_user_id={conversation.other_user_id}
</Conversation>
);
});
return (
<div className="conversationList">
{conversationNodes}
</div>
);
}
});
var ConversationBox = React.createClass({
loadConversationsFromServer: function() {
return $.ajax({
url: this.props.url,
dataType: 'json',
success: function(data) {
this.setState({data: data.conversations});
}.bind(this),
error: function(xhr, status, err) {
console.error(this.props.url, status, err.toString());
}.bind(this)
});
},
getInitialState: function() {
return {data: []};
},
/* Taken from
https://facebook.github.io/react/docs/reusable-components.html#mixins
clears all intervals after component is unmounted
*/
componentWillMount: function() {
this.intervals = [];
},
setInterval: function() {
this.intervals.push(setInterval.apply(null, arguments));
},
componentWillUnmount: function() {
this.intervals.map(clearInterval);
},
componentDidMount: function() {
this.loadConversationsFromServer();
this.setInterval(this.loadConversationsFromServer, this.props.pollInterval);
},
render: function() {
return (
<div className="conversationBox">
<h1>Conversations</h1>
<ConversationList data={this.state.data} />
</div>
);
}
});
$(document).on("page:change", function() {
var $content = $("#content");
if ($content.length > 0) {
React.render(
<ConversationBox url="/conversations.json" pollInterval={20000} />,
document.getElementById('content')
);
}
})
TypeError: .map is not a function - React application
I believe it's because .map is a method for Array prototypes, not for Objects (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map)
You can return the array from the object by using data.data instead of just data:
...
const getProfile = async () => {
setLoading(true);
const response = await fetch("https://reqres.in/api/users");
const data = await response.json();
setProfile(data.data); // probably a safer way to do this, but if you console.log(data) you'll see an object is being returned, not an array.
setLoading(false);
};
...
Why is my map function in React giving me an error? (...is not a function)
You have to convert your card object to an array in order to use the map function available for Arrays.
Try the following for your Card component:
import React from "react";
function Card(props) {
return (
<div key={props.id}>
<h1>{props.title}</h1>
<p>{props.content}</p>
</div>
)
}
function List(props) {
console.log(Array.isArray(props.card) ? "true": "false");
return (
<div className="App-list">
<section className="List">
<header className="List-header">
<h2>{props.header}</h2>
<div className="List-cards">
{Object.entries(props.card).map((item) => {
console.log('item', item);
return (
<Card key={item[1].id} id={item[1].id} title={item[1].title} content={item[1].content} />
);
})}
</div>
</header>
</section>
</div>
);
}
export default List;
References:
JavaScript Tutorial Website. Convert an Object to an Array in JavaScript. https://www.javascripttutorial.net/object/convert-an-object-to-an-array-in-javascript/. (Accessed November 22, 2020)
React map not a function
Assuming the data fetching at state updates are correct, you've a few issues with props handling.
GetSongsRequest
needs to access the props correctly. Resolve this by destructuring from the props object.
import React, { useState, useEffect } from "react";
import { useAuth0 } from "@auth0/auth0-react";
function GetSongsRequest({ listedSongs, addListedSongs }) {
const { user } = useAuth0();
const [songs, setSongs] = useState([])
useEffect(() => {
if (user) {
const requestOptions = {
method: 'GET'
};
let url = '#' + user.sub
fetch(url, requestOptions)
.then(response => {
return response.json();
}).then(jsonResponse => {
setSongs(jsonResponse)
localStorage.setItem('songsStorage', JSON.stringify(jsonResponse))
}).catch (error => {
console.log(error);
})
}
}, [user])
return (
<ul>
{songs.map((el) => (
<li key={el} className="tailwindCssStuff"
onClick={ () => addListedSongs(listedSongs.concat(el)) }>
{el[0]}</li>
))}
</ul>
)
}
Similarly, SongsInList
needs to destructure the listedSongs
props which is the array you want to map.
function SongsInList({ listedSongs }) {
return (
<ul>
{listedSongs.map((el) => (
<li key={el} className="tailwindCssStuff">
{el[0]}
</li>
))}
</ul>
)
}
Main is ok.
export default function Main() {
const [listedSongs, addListedSongs] = useState([])
return (
<div>
<div id="userContent" className="tailwindCssStuff">
<h1 className="tailwindCssStuff">Songs</h1>
<div id = "vertical-content">
<GetSongsRequest listedSongs={listedSongs} addListedSongs={addListedSongs} />
</div>
</div>
<div id="liveList" className="tailwindCssStuff">
<h1 className="tailwindCssStuff">List</h1>
<div id = "vertical-list">
<SongsInList listedSongs={listedSongs} />
</div>
</div>
</div>
)
}
React Js : .map is not a function
You are setting your suppliers state to be an object in this line:
.then(x => setstate({suppliers:x.data}))
Instead, let the setstate handle the change of suppliers and only pass the variable like this:
.then(x => setstate(x.data))
assuming x.data is an array.
You can also change the following line suppliers.map((supplier)=>supplier)
to (suppliers || []).map((supplier)=>supplier)
this way in case x.data or suppliers get changed to null\undefined your app will not crash.
Also as mentioned above the usage of setstate is not recommended. I'd advise you read about this topic here: https://reactjs.org/docs/hooks-state.html
".map is not a function" error in react.js
Try this
{state.stage && state.stage.map(.........
i got an error: Uncaught (in promise) TypeError: cartItems.map is not a function. The above error occurred in the <CartScreen> component:
This error occurs because your data is not an array. The .map() function only works with arrays. First, you'll need to confirm your data type. Second, you'll need to transform your data into an array.
You should check your cartItems type and change your state to be sure to have an array.
source : https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Global_Objects/Map
Related Topics
How to Disable Eslint Rule Max Line Length for Paragraph in <Template> of Vue.Js
How to Count Unique Value from Object of Array in JavaScript
How to Iterate Through Json Nested Objects With Ngfor
Jest Encountered an Unexpected Token: Syntaxerror: Unexpected Token {
Javascript - Remove Milliseconds from Date Object
Prevent Form Submission on Enter Key Press
Mongodb Get Data to Display in HTML
Change Specific Button Text on Click Inside Ngfor
Formdata Created from an Existing Form Seems Empty When I Log It
How to Get the Index from a Json Object With Value
Best Way to Show a Loading Spinner/Gif While My React Component Is Fetching Via Ajax
How to Use Zindex in React-Native
How to Change Div Order in JavaScript
How to Remove the X-Axis from a Bar Chart Produced by Google'S Visualization API
In Nest.Js, How to Get a Service Instance Inside a Decorator
Resize a Base-64 Image in JavaScript Without Using Canvas