Consider the code below:
componentDidMount(){
const id = localStorage.getItem('id');
fetch(`http://localhost:9000/api/calendar/list/${id}`,)
.then((resp)=>{
resp.json().then((res)=>{
this.setState({
data: res.data.map(item => {
return {
title: item.title,
startDate: new Date(item.startDate),
endDate: new Date(item.endDate),
eventId: item.eventType // from api it provide on string but I need to convert it in to an integer
};
})
});
})
})
}
The result from the API are here:
So on the frontend js, I need to set the eventId to a number like Conference in num 1, Launching in num 2, Trade Shows in num 3. Is it any way I can do it ?
You can create an object to map the string to a number like this, where item1
and item2
are examples of what your API data could be:
const item1 = {
userId: 1,
startDate: 123456,
endDate: 123456,
eventType: 'Conference'
};
const item2 = {
userId: 2,
startDate: 123456,
endDate: 123456,
eventType: 'Launching'
};
const map = { Conference: 1, Launching: 2, Trade: 3 };
console.log(map[item1.eventType]); // eventId will be 1 for Conference
console.log(map[item2.eventType]); // eventId will be 2 for Launching
In your code this would be
const map = { Conference: 1, Launching: 2, Trade: 3 };
fetch(`http://localhost:9000/api/calendar/list/${id}`,)
.then((resp)=>{
resp.json().then((res)=>{
this.setState({
data: res.data.map(item => {
return {
title: item.title,
startDate: new Date(item.startDate),
endDate: new Date(item.endDate),
eventId: map[item.eventType]
};
})
});
})
})