Im fetching data from api using axios.
I have array of objects.
I would like to fetch objects inside array.
Here is api : https://51fgc922b7.execute-api.ap-south-1.amazonaws.com/dev/productpreview?product_id=122003
enter image description here
Here is what i tried !
useEffect(() => {
if (props.product_id) {
axios.
get(`https://51fgc922b7.execute-api.ap-south-1.amazonaws.com/dev/productpreview?product_id=${props.product_id}`)
.then((res) => {
console.log(res.data)
setModelData(res.data.data[0])
})
.catch((error) => {
setIsErrorImage(true)
})
}
}, []);
Im able to fetch data but what im trying to achive is that, there are three objects with camera objects called 0,1,2 and i want to fetch them.
I'm not sure about your requirement but as far as I understood you just want the array of objects from the data you get. You can get that simply by traversing the object like
const cameraData = res.data.reduce((acc,el) => [...acc, ...el.camera], [] )
console.log(res.data) if correct ,
setModelData(res.data)
and in return example ;
modelData.map((item)=> {
return (
<div> {item.camera.map((data)=>{
return (
<div> {data.camera_beta} </div>
)
})}
</div> )})
this is what i want to tell
const [modelData, setModelData] = useState([
{
name: 'Electronics',
slug: 'electronics',
count: 11,
items: [
{ name: 'Phones', slug: 'phones', count: 4 },
{ name: 'Tablets', slug: 'tablets', count: 5 },
{ name: 'Laptops', slug: 'laptops', count: 2 },
],
},
{
name: 'Clothing',
slug: 'clothing',
count: 12,
items: [
{ name: 'Tops', slug: 'tops', count: 3 },
{ name: 'Shorts', slug: 'shorts', count: 4 },
{ name: 'Shoes', slug: 'shoes', count: 5 },
],
}
])
you have data like this.
this way you set the data into setmodeldata in useeffect.
in useffect after set
console.log(modelData) and
console.log(modelData[0])
you can see the difference between the two.one comes in the form of an object and the other as an array.
at most you can map them
Related
Why can't I push in my <option> when I get the response.data?
type State = {
companyManagerMap: null | Map<string, string[]>
}
useEffect(() => {
AdminListManager()
.then((response) => {
const { data } = response.data
console.log( { data });
setState((s) => ({
...s,
companyManagerMap: new Map(
Object.keys(data).map((key) => [key, data[key]])
),
}))
})
.catch(showUnexpectedError)
}, [showUnexpectedError])
data format
{"total":2,"data":[{"id":1,"name":"newspeed","contains_fields":[{"id":1,"name":"Official"}]},{"id":2,"name":"YAMAHA","contains_fields":[{"id":3,"name":"US"}]}]}
You are using your .map and Object.keys wrong
Look here at where you iterate over your Object keys properly :)
const data = {
total: 2,
data: [
{ id: 1, name: 'newspeed', contains_fields: [{ id: 1, name: 'Official' }] },
{ id: 2, name: 'YAMAHA', contains_fields: [{ id: 3, name: 'US' }] },
],
};
//now iterate over it properly
data.data.map((item) => {
Object.keys(item).map((key) => {
console.log(item[key]);
});
});
console.log will return this output
1
newspeed
[ { id: 1, name: 'Official' } ]
2
YAMAHA
[ { id: 3, name: 'US' } ]
I'm guessing you want to add the new data from your res.data to a state
So you can do something like this:
const fetchData = async () => {
try {
const res = await AdminListManager()
//do data manipulation over objects and set new state
} catch (error) {
showUnexpectedError()
}
}
useEffect(()=> {
fetchData()
}, [showUnexpectedError])
I am mapping out item values which is an array
const mappedItems = items.map(item => {
return (
<div key={item.id}>
<h2>{item.name}</h2>
<h2>{item.quantity}</h2>
</div>
)
});
What get outputted is like this:
Fun Mix
1
Potato Chips
5
I am trying to insert the items to my DB from my API, and the structure of the fields is like this:
Items: {
name: //Since the mapped value of the name is an array how can I store all the mapped names in this name field which is an object
quantity: //Same for quantity
},
In my backend controller, I am getting the value like this:
const order = new Order({
Items: req.body.Items,
});
My DB structure where the items are being inserted to is like this
Items: [
{
name: { type: String, required: true },
quantity: { type: Number, default: },
}
]
You could do like this (unless I missunderstood what you are trying to do):
const backendItems = items.map(item => {name:item.name, quantity: item.quantity})
So in the end, backendItems looks like this with your example:
backendItems: [
{
name: "Fun mix",
quantity: 1,
},
{
name: "Potato Chips",
quantity: 5,
}
]
Assume that this state has initial data like this
const [options, setOptions] = useState({
ProcessType: [
{ value: 1, label: 'Type1' }, { value: 2, label: 'Type2' }
],
ResponsibleUser: [
{ value: 1, label: 'User1' }, { value: 2, label: 'User2' }
]
});
The following function will be called again and again when a post/put called
Help me to complete the commented area as described there.
const fetchProcesses = async () => {
await axios.get(`${process.env.REACT_APP_SERVER_BASE_URL}/processes/`)
.then((result) => {
/*
I want here to clear the existing data in options.ProcessType and
map result.data as { value: result.data.id , label: result.data.name },....
and push/concat it into to options.ProcessType but i want to keep the data
inside options.ResponsibleUser unchanged.
result.data is an array of objects like this,
[
{ id: 1 , name: 'Type1', desc : 'desc1', creator: 3, status: 'active' },
{ id: 2 , name: 'Type2', desc : 'desc2', creator: 6, status: 'closed' },
.....
.....
]
*/
})
}
Here is a solution
const fetchProcesses = async () => {
await axios.get(`${process.env.REACT_APP_SERVER_BASE_URL}/processes/`)
.then((result) => {
// solution
setOptions({ResponsibleUser: [...options.ResponsibleUser], ProcessType: result.data.map(row => ({value: row.id, label: row.name}))})
})
}
This doesn't seem to be working when i try to populate my data with the data i fetched from my API. I am currently fetching the data, storing it in my array called ProductsAndAirlines which i instantiated in my constructor, then I am setting the data values dynamically in my options,but currently it doesn't. It only inserts the first static value which is PBS.
Code
getProductsAndAirlines = _ => {
fetch('http://localhost:4000/allProductAndAirlineValuesInJira')
.then(res => res.json())
.then( res =>
this.setState({ ProductsAndAirlines: res.data }
))
.catch(err => console.error(err))
}
componentDidMount() {
this.getAirlines();
this.getProductsAndAirlines();
setTimeout(() => {
this.setState({ show: true });
}, 10);
}
const optionsProduct = [
ProductsAndAirlines && ProductsAndAirlines.projects && Object.keys(ProductsAndAirlines.projects).map((issue, i) => (
ProductsAndAirlines.projects[0].issuetypes[0].fields.customfield_11600.allowedValues && Object.keys(ProductsAndAirlines.projects[0].issuetypes[0].fields.customfield_11600.allowedValues ).map((product, product_index) => (
{value: ProductsAndAirlines.projects[0].issuetypes[0].fields.customfield_11600.allowedValues[product_index].value, label: ProductsAndAirlines.projects[0].issuetypes[0].fields.customfield_11600.allowedValues[product_index].value}
))
))
render(){
<Select
placeholder = {this.state.Product}
onChange={this.handleChangeProduct}
options={optionsProduct()}
/>
}
It's, probably, because your map function is wrong somehow. If you take a deep look you can check, for each key in ProductsAndAirlines.projects, the map function is returning an entirely new array. in the end, the options are being like
[
[{ value: 'PBS', label: 'PBS' },
{ value: 'Pairing', label: 'Pairing' },
{ value: 'MPP - Insight', label: 'MPP - Insight' },
{ value: 'BLISS', label: 'BLISS' },
{ value: 'Shiftlogic', label: 'Shiftlogic'}
]],
[{ value: 'PBS', label: 'PBS' },
{ value: 'Pairing', label: 'Pairing' },
{ value: 'MPP - Insight', label: 'MPP - Insight' },
{ value: 'BLISS', label: 'BLISS' },
{ value: 'Shiftlogic', label: 'Shiftlogic'}
]]
]
This is my api:
exports.getService = function(req, res) {
var limit = 10; // number of records per page
var offset = 0;
Service.findAndCountAll({
raw: true,
where: {
shop: req.user.shop
}
}).then((data) => {
var page = req.params.page; // page number
var pages = Math.ceil(data.count / limit);
offset = limit * (page - 1);
Service.findAll({
// raw: true,
limit: limit,
offset: offset,
$sort: {
id: 1
},
where: {
shop: req.user.shop
},
include: [{
model: Categoryservice,
attributes: ['id'],
include: [{
model: Category,
attributes: ['id', 'name'],
}]
}],
}).then(function (services) {
var services=JSON.parse(JSON. stringify(services));
console.log('=====stringify==========>>',services);
var arr = services.categoryservices.map(item => item.category.id)
services.cats = arr;
delete services.categoryservices;
console.log('only for the testing========>',services);
res.status(200).json({
'result': services,
'count': data.count,
'pages': pages
});
});
}).catch(function(error) {
res.status(500).send('Internal Server Error');
});
};
I am using map in last then fuction ,
It contains a error map undefined in the server..
I want want a out like below given json using the map fuction.
Actually i need this out put:
{
"id": 2,
"service": "mobile",
"min": "20",
"per": "10",
"tax": "1",
"cats": [
1,
2
]
}
my JSON. stringify(services) out put is:
=====stringify==========>> [ { id: 2,
username: null,
name: null,
image: null,
service: 'mobile',
shop: '$2a$10$NWpbmgtzQAxRZ1ugvdC7LOlorBU36xoGHm1L.k.KmFqDO/7oSmBLu',
min: '20',
per: '10',
tax: '1',
activity: null,
createdAt: '2018-03-14T07:30:57.000Z',
updatedAt: '2018-03-14T07:30:57.000Z',
categoryservices: [ [Object], [Object] ] },
{ id: 1,
username: 'sam',
name: 'New Service',
image: '/images/uploads/22-Feb-2018/f96334384cd78754454c5e4e05e20fc0-dragon_pattern_red_black_9666_1920x1080.jpg',
service: 'battery',
shop: '$2a$10$NWpbmgtzQAxRZ1ugvdC7LOlorBU36xoGHm1L.k.KmFqDO/7oSmBLu',
min: '5',
per: '1',
tax: '1',
activity: '2018-03-14T06:01:36.000Z',
createdAt: '2018-03-14T06:01:36.000Z',
updatedAt: '2018-03-14T06:01:36.000Z',
categoryservices: [] } ]
I was beginner of using map function,
so,I am confused in map ,
so please give any solution to this problem.
You are stringifying your array that comes back. You can't do that if you plan to use .map on it. Remove that code and try again.
.then(function (services) {
var arr = services.categoryservices.map(item => item.category.id)
services.cats = arr;
delete services.categoryservices;
console.log('only for the testing========>',services);
res.status(200).json({
'result': services,
'count': data.count,
'pages': pages
});
});
I think we are missing something because the output you pasted doesn't have the category.id attribute that you are returning from the item passed in to map. Is that what you are trying to target? That's off topic, but this code may not work for what you are trying to achieve but will run the map though.
Looks like services is an array, based on the console.log. If you want the id's of all categories, you can do
let categoryIds = [];
categoryIds = services.reduce((categoryIds, service) => {
let ids = service.categoryservices.map(category => category.id);
for(let id of ids) {
if(categoryIds.indexOf(id) === -1) {
categoryIds.push(id)
}
}
return categoryIds;
}, categoryIds);
If you want to have category ids as cats in each service, you can do,
var services=JSON.parse(JSON. stringify(services));
services.forEach(service) => {
service.cats = service.categoryservices.map(category => category.id);
delete service.categoryservices;
});
res.status(200).json({
'result': services,
'count': data.count,
'pages': pages
});
Hope this helps!