0
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>
      );
    }
1
  • Please show your AppContext.Provider Commented Jul 31, 2019 at 17:50

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Where would i add that tho?
as i wrote, check ../App/AppProvider file.
0

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.