Reputation: 13
I have a component that i want to reuse by passing the state as props, but i need to loop through the state first and get the values. I tried using object.keys() but i think im doing something wrong.
Heres my state:
const [savingSources, setSavingSources] = useState({
exams: {
name: "Your Exams",
checked: false,
loading: false,
savings: []
},
pharmacy: {
name: "Farmácias",
checked: false,
loading: false,
savings: []
},
pagVolta: {
name: "PagVolta",
checked: false,
loading: false,
savings: []
}
});
And here's where i try to loop, but im unable to get the values inside each key
{Object.keys(savingSources).map((source, index) => {
return (
<SavingInformation
key={index}
name={source.name}
checked={source.checked}
savings={source.savings}
loading={source.loading}
/>
);
})}
Everything besides the source var returns undefined and i tried passing only the source and then getting the props on the component but it only returns the name that is stored on 'source'.
Im very new to React and i wanted this approach because im trying to make reusable components, but im stuck trying to figure this out.
Thanks a lot guys!
Upvotes: 1
Views: 57
Reputation: 856
Object.keys will only give you the first level keys of the object (e.g. : exams, pharmacy, pagVolta). You can then use those keys to access the state like savingSources[source]['name']
Upvotes: 0
Reputation: 3887
Object keys is going to return an array of the object fields. You will need to use these fields/keys to access the object values inside map.
{Object.keys(savingSources).map((key, index) => {
return (
<SavingInformation
key={index}
name={savingSources[key].name}
checked={savingSources[key].checked}
savings={savingSources[key].savings}
loading={savingSources[key].loading}
/>
);
})}
Upvotes: 4