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
- What can I do to apply a prop to only one item in a map/array on the render method of a React component?
- show two row and four items per row
- Testing Redux Enzyme: Component doesn't re-render after state has changed
- Argument of type 'HTMLElement | null' is not assignable to parameter of type 'Element'. Type 'null' is not assignable to type 'Element'.ts(2345)
- Render dynamic components by names in React
- React typescript with axios response type
- Using the isAbsolute() function in Javascript not working as expected
- Collapse navbar sooner then 576px
- React native (expo) web view Error net::ERR_CACHE_MISS
- Application does not fetch access token from cache using MSAL (react-aad-msal)
- Fetching data keys from an api data set
- Pass data from react.js Store to Component in a clean way following flux pattern
- Google Firebase deploy gives - Error: HTTP Error: 404, Requested entity was not found
- Enzyme – test event handler function who needs an arbitrary `target` property
- React Application Requiring Access to 3000+ Entries from Contentful API
- Injecting dynamic HTML in React - CSS is not working
- JS how to add hours and minutes to scheduled date
- ignore values from react hook returned array -
- React Bootstrap error: 'AccordionCollapseProps' is not exported from './AccordionCollapse'
- Call back not working when Link is clicked in react router
- How to properly fit an image into a div in HTML and CSS using ReactJS
- react-spring Transition does not animate enter state
- React external script console log not showing
- Progress bar with react-bootstrap is not showing up
- React - enable/disable component when we click on one img
- React Router Link Right Click does not work
- How to clone multiple children with React.cloneElement?
- Access custom component props and URL parameters from react-router-dom in TypeScript
- change setInterval timings from within the interval
- Single page applications and rendering private pages