Reputation: 490
I've been looking for a similar question and none of the ones I found did actually match my problem...
EDIT:
The whole idea is to develop a reusable dropdown component where I pass the items straight through props. These items must be objects with a key (for field value) and display property (for value text).To make the conversion, I use the itemify
function. All of this code is present in the form component that will include the dropdown.
The problem goes like this:
I have an array of objects I fetch from the server. The goal is to keep this array of objects ("old objects") and also to create another one ("newObjects"). This new array should contain new objects converted from the first array, but where:
newObject.key = oldObject.someProperty
newObject.display=oldObject.someOtherProperty
To make this conversion I created the "itemify" function.
Now, the actual results. First, I fetch de data from the server Then I create another array by converting the one obtained by the fetch API.
getProfiles = async () => {
const result = await fetch(apiConfig.profilesAPI);
const body = await result.json();
if (body.data.length>0){
let temp = body.data;
console.log(temp);
let buffer = body.data.map(x=>itemify(x,"id","desc"));
this.setState((state,props)=>({
profiles: body.data,
profileItems: buffer
}));
}
}
EDIT: this is my full itemify
function
function itemify(obj,id,display) {
let retVal = {
key: obj[id],
display: obj[display]
}
console.log("obj: "+obj);
console.log("retVal: "+retVal);
return retVal;
// return {key:obj[id],display:obj[display]} //prior version had only this line
}
If I go checkout the console, I have this:
First log is from the first code snippet
console.log(temp);
Tell me if you need more code. This part of the code is not on github yet.
Upvotes: 1
Views: 97
Reputation: 490
Problem solved!
As I explained, I was trying to render a DropDown list into a parent component, which was a form. The final result was that the dropdown was empty.
First, I realised I was making a mistake on the way I was logging to the console. Wrong way:
console.log("object " + object);
Correct way:
console.log("object",object);
I thought I was doing anything wrong when converting objects. After all everything was right all along with the objects and the conversion.
I found out that I ran into some confusion between managing state and props.
I was loading props sent from the form into state of the child component (dropdown) - which I now realise it maybe doesn't make much sense.
Where I was rendering the array with the items using
this.state.items.map(x=>renderItems(x))
I replaced with
this.props.items.map(x=>renderItems(x))
And it now works! After all, why manage this into state...props is enough. Lesson learnt!
Upvotes: 1