Reputation: 21
TypeError: Cannot read property 'map' of undefined
This error keeps coming up and will not let me run my website. Any help or assistance would be great. I just need to figure out what exactly to change in order to get this running.
import React from "react";
import styled from "styled-components";
import { AppContext } from "../App/AppProvider";
import PriceTile from "./PriceTile";
export default function() {
return (
<AppContext.Consumer>
{({ prices }) => (
<PriceGrid>
{prices.map((price, index) => (
<PriceTile key={`priceTile-${index}`} index={index} price={price} />
))}
</PriceGrid>
)}
</AppContext.Consumer>
);
}
Upvotes: 0
Views: 38
Reputation: 12071
You can check for the existence of prices
before doing the map:
<AppContext.Consumer>
{({ prices }) => (
<PriceGrid>
{prices && prices.map((price, index) => (
<PriceTile key={`priceTile-${index}`} index={index} price={price} />
))}
</PriceGrid>
)}
</AppContext.Consumer>
...or you could default prices
to an empty array:
<AppContext.Consumer>
{({ prices = [] }) => (
<PriceGrid>
{prices.map((price, index) => (
<PriceTile key={`priceTile-${index}`} index={index} price={price} />
))}
</PriceGrid>
)}
</AppContext.Consumer>
...or, better still, do both:
<AppContext.Consumer>
{({ prices = [] }) => (
<PriceGrid>
{prices && prices.map((price, index) => (
<PriceTile key={`priceTile-${index}`} index={index} price={price} />
))}
</PriceGrid>
)}
</AppContext.Consumer>
Upvotes: 0
Reputation: 35493
Probably you are not providing an initial value to your Context
,
Check in ../App/AppProvider
there is some call to React.createContext
, check that you provide an object with prices
that is an empty array.
Upvotes: 1