I am trying to connect to the USDA Food Central database using an API.
let uri = encodeURI(`https://api.nal.usda.gov/fdc/v1/foods/search?api_key=${MY_API_KEY}&query=${search}`)
I want to use the API to map certain fields.
class AddFoodItemList extends Component {
static contextType = AddFoodContext;
render() {
const listItems = this.context.FoodSearch.map((foods) =>
<FoodItem
key={foods.brandOwner}
brandOwner={foods.brandOwner}
fdcId={foods.fdcId}
/>
);
return (
<div id="AddFoodItemList">
{listItems}
</div>
);
}
}
export default AddFoodItemList;
The returned JSON is this screenshot attached: Returned JSON
I am getting an error, TypeError: Cannot read property 'map' of undefined. Why do you think this is the case? Any sort of help or suggestions are appreciated!
You are attempting to access a property
FoodSearchon the value of yourAddFoodContextprovider. The error tells you that this property isundefined. If theobjectin your screenshot is thevalueof your context then you want to access the propertyfoodsinstead. This is anarraywhose elements are objects with propertiesbrandOwnerandfdcId.On your first render this data might now be loaded yet, so you should default to an empty array if
foodsisundefined.It's honestly been a long time since I've used contexts in class components the way that you are doing it. The style of code is very dated. How about using the
useContexthook to access the value?Here's a complete code to play with - Code Sandbox Link