score:201
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')
);
}
})
score:-1
try componentDidMount()
lifecycle when fetching data
score:0
Add this line.
var conversationNodes =this.props.data.map.length>0 && this.props.data.map(function(conversation, index){.......}
Here we are just checking the length of the array. If the length is more than 0, Then go for it.
score:0
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination', 'PAGE_SIZE': '2',
I delete that code line in setting it to fix it
score:1
You don't need an array to do it.
var ItemNode = this.state.data.map(function(itemData) {
return (
<ComponentName title={itemData.title} key={itemData.id} number={itemData.id}/>
);
});
score:1
You need to convert the object into an array to use the map
function:
const mad = Object.values(this.props.location.state);
where this.props.location.state
is the passed object into another component.
score:1
As mentioned in the accepted answer, this error is usually caused when the API returns data in a format, say object, instead of in an array.
If no existing answer here cuts it for you, you might want to convert the data you are dealing with into an array with something like:
let madeArr = Object.entries(initialApiResponse)
The resulting madeArr
with will be an array of arrays.
This works fine for me whenever I encounter this error.
score:1
I had a similar error, but I was using Redux for state management.
My Error:
Uncaught TypeError: this.props.user.map is not a function
What Fixed My Error:
I wrapped my response data in an array. Therefore, I can then map through the array. Below is my solution.
const ProfileAction = () => dispatch => {
dispatch({type: STARTFETCHING})
AxiosWithAuth()
.get(`http://localhost:3333/api/users/${id here}`)
.then((res) => {
// wrapping res.data in an array like below is what solved the error
dispatch({type: FETCHEDPROFILE, payload: [res.data]})
}) .catch((error) => {
dispatch({type: FAILDFETCH, error: error})
})
}
export default ProfileAction
score:1
You should try this:
const updateNews = async()=>{
const res= await fetch('https://newsapi.org/v2/everything?q=tesla&from=2021-12-30&sortBy=publishedAt&apiKey=3453452345')
const data =await res.json();
setArticles(data)
}
score:1
Create an array from props data.
let data = Array.from(props.data)
Then you can use it like this:
{ data.map((itm, index) => {
return (<span key={index}>{itm}</span>)
}}
score:2
If you're using react hooks you have to make sure that data
was initialized as an array. Here's is how it must look like:
const[data, setData] = useState([])
score:4
Sometimes you just have to check if api call has data returned yet,
{this.props.data && (this.props.data).map(e => /* render data */)}
score:6
I had the same problem. The solution was to change the useState initial state value from string to array. In App.js, previous useState was
const [favoriteFilms, setFavoriteFilms] = useState('');
I changed it to
const [favoriteFilms, setFavoriteFilms] = useState([]);
and the component that uses those values stopped throwing error with .map function.
score:8
It happens because the component is rendered before the async data arrived, you should control before to render.
I resolved it in this way:
render() {
let partners = this.props && this.props.partners.length > 0 ?
this.props.partners.map(p=>
<li className = "partners" key={p.id}>
<img src={p.img} alt={p.name}/> {p.name} </li>
) : <span></span>;
return (
<div>
<ul>{partners}</ul>
</div>
);
}
- Map can not resolve when the property is null/undefined, so I did a control first
this.props && this.props.partners.length > 0 ?
score:12
More generally, you can also convert the new data into an array and use something like concat:
var newData = this.state.data.concat([data]);
this.setState({data: newData})
This pattern is actually used in Facebook's ToDo demo app (see the section "An Application") at https://facebook.github.io/react/.
score:56
You need to create an array out of props.data
, like so:
data = Array.from(props.data);
then will be able to use data.map()
function
Source: stackoverflow.com
Related Query
- REACT Uncaught TypeError .then is not a function
- When Using Redux Saga with React Get This Error .. Uncaught TypeError: getPosts is not a function
- React why is this simple array map function not returning anything?
- Uncaught TypeError rendering <Router> using React Router in ES6: type.toUpperCase is not a function
- Map function not working while passing props into React component (TypeScript, React and Next.js)
- Trying to map data through props to React Bootstrap Accordion - data not displaying?
- Uncaught TypeError: this.state.people.map is not a function in react js while using the map function
- diaplays same data in react js, if condition not working or working but map function takes all value without sorting
- Can not access react props data when I try to access it. Getting TypeError error
- map function not working for API data in useEffect - React Hooks
- React JS TypeError - this is not a function
- React - Rails Uncaught TypeError 'map' of data not defined
- React display data from object TypeError: value map is not a function
- Uncaught TypeError: this.state.value.map is not a function when using React map
- How to fix map is not function even there is already set data in the useState using React Hook
- React : Can't find solution for this error : Uncaught TypeError: clients.map is not a function
- React JS - Uncaught TypeError: this.props.data.map is not a function
- TypeError dispatcher.useState is not a function when using React Hooks
- Error with basic React Example: Uncaught TypeError: undefined is not a function
- Uncaught TypeError: create is not a function using useEffect React Hook with AJAX request
- React JS Uncaught Reference Error: function not defined
- How to debug this error: Uncaught (in promise) Error: Objects are not valid as a React child
- React TypeError this._test is not a function
- map function not working in React
- How to fix TypeError _interopRequireDefault is not a function in Create React App
- Uncaught TypeError: *** is not a function in a React component
- Uncaught TypeError: _moment2.default.date is not a function in React app
- React Uncaught TypeError: this.state.messages.map is not a function
- React - State Hook map is not a function
- React - State Hook map is not a function
More Query from same tag
- React router with lazy and Suspense always falls back on wildcard route on page refresh
- How to get event pixel when I have coordinates in database
- image not uploading in proper size on aws s3 server
- "store is not defined" Firebase and ReactJS error
- eCharts stacked bar graph - Y axis
- React using reactstrap navbar: how to add and remove class on navbar tag when window scrolls
- React Native: getter function in functional component?
- How do I get a list of react.js routes from a database?
- Clear Search value on focus out of a Multiselect - multiselect-react-dropdown (React JS)
- Can i set default Object value in select
- mapStateToProps is not running
- reactjs, json, image loading
- Persist Material-UI Selections With Redux Data
- <Table> in react-bootstrap - SyntaxError
- React multiple api calls in one action
- How to narrow down union of generic types in Typescript?
- How to specify in which pages stripejs script can be loaded?
- how can i upgrade it to react-router-dom v6
- React-Webpack. Update className with css-loader
- Why I get null in the first click and in the second or any click after it i get input element correct, react js?
- How to read json file from my src folder in my react app using webpack-dev-server?
- Number of console logs in component body not equal to number of rerenders?
- Use react-redux connect in typescript
- Setting a default value to an input field in React?
- apollo graphql UI is not updating after refetch
- how to handle %20 in Link URL
- How change the format of checkbox in react final form
- How to disable strict mode while bundling React using webpack
- Component not loading when i change link in nested route in react-router
- What are the advantages of 'Stateless Function Components' over 'ES6 Class Components'?