Reputation: 87
I have a problem with my code, I use reactJs and redux.
my error : TypeError: demo.map is not a function
my action:
// DEMO
export const demoFetchRequest = () => {
return {
type: DEMO_FETCH_REQUEST,
};
};
export const demoFetchSuccess = (demo) => {
return {
type: DEMO_FETCH_SUCCESS,
demo,
};
};
export const demoFetchError = (error) => {
return {
type: DEMO_FETCH_ERROR,
error,
};
};
my reducer:
const initialState = {
loading: false,
demo: [],
error: null,
};
const demo = (state = initialState, action) => {
switch (action.type) {
case DEMO_FETCH_REQUEST:
return { ...state, loading: true };
case DEMO_FETCH_SUCCESS:
return { ...state, loading: false, demo: action.demo };
case DEMO_FETCH_ERROR:
return { ...state, loading: false, error: action.error };
default:
return state;
}
};
my data:
const demoCompletedData = [
{
id: 1,
marketId: "1111-1111-1111-1111",
title: "Autonomous car",
picture: "https://th?id=OIP.fdvfdvfdvfdvfd&pid=Api",
language: "English",
flag: "🇬🇧",
completed: true,
date: "22/01/2019 10:30",
rate: 9.1,
categories: {
de: 1,
sp: 2,
uk: 0,
fr: 1,
us: 4,
},
},
{
id: 2,
my componentDidMount :
componentDidMount() {
this.fetchDemo();
this.fetchUser();
}
my fetch in front:
fetchDemo() {
this.props.demoFetchRequest();
const { marketId } = this.props.match.params;
axios.get(`/api/v1/passport-authenticate/market/${marketId}`)
.then((res) => { return res.data; })
.then(demo => this.props.demoFetchSuccess(demo))
.catch(error => this.props.demoFetchError(error));
}
my return:
const { demo } = this.props;
my render
<h5>{demo.title}</h5>
<p>
Demo
{' '}
{demo.flag}
</p>
{demo.map((el) => {
return (
<div>
{Object.keys(el.categories).map((key) => {
return (
<p>
{key}
:
{el.categories[key]}
</p>
);
})}
</div>
);
})}
and when I change Object.keys() I have another error TypeError: can't convert undefined to object
{Object.keys(demo).map((el) => {
return (
<div>
{Object.keys(el.categories).map((key) => {
return (
<p>
{key}
:
{el.categories[key]}
</p>
);
})}
</div>
);
})}
can you help me ?
Upvotes: 1
Views: 38
Reputation: 33183
Map is a method on the Array prototype.
The code demo.map
will only work if demo is an array, but in your code it appears to be an object.
It looks like your meant your render method to be slightly different, perhaps like:
<h5>{demo.title}</h5>
<p>
Demo
{' '}
{demo.flag}
</p>
{demo.categories.map((el) => {
return (
<div>
<p>
{el}
</p>
</div>
);
})}
I also just noticed that your categories is an object, not an array, so the part of your render method that deals with categories should be something like this:
{demo.categories && Object.keys(demo.categories).map((el) => {
return (
<div>
<p>
{el.categories[key]}
</p>
</div>
);
})}
There are some things to note with the above:
Upvotes: 1