0

I'm fetching data from an API and I'm using React and Redux to do so. I am successfully getting data from the API. Here's the console.log with the output:

console.log(this.props.customer.data) enter image description here

But I can't get it to display in my React app. I bet my problem is really basic, but I really don't understand why this is not working.

I tried doing this inside of return:

{this.props.customer.data.map(customers => <p>{customers.name}</p>)}

But I'm only getting the error: TypeError: Cannot read property 'map' of undefined.

If anyone know why this is happening, please let me know! Thanks!

(I know that I should not have my props in singular, because it represents multiple customers..)

8
  • Is it failing when first trying to render? Do you have a default value for this.props.customer.data? Commented Aug 2, 2017 at 17:37
  • What do you mean with default value? Commented Aug 2, 2017 at 17:55
  • I mean that the initial state for customer.data should be an array. Commented Aug 2, 2017 at 17:59
  • Inside my reducer I got this: export function customer(state = [], action) Commented Aug 2, 2017 at 18:00
  • Is that setting customer.data to an array or customer to an array? Commented Aug 2, 2017 at 18:00

3 Answers 3

3

The problem is that you don't have an initial value for customer.data. You mentioned in another comment that your reducer is setup like this:

export function customer(state = [], action) {
  ...
}

which is setting customer to an array. Instead, do something like this in your reducer:

const initialState = {
  data: [] // <-- Default value for customer.data is an empty array
};

export function customer(state = initialState, action) {
  ...
}
Sign up to request clarification or add additional context in comments.

2 Comments

The funny part is that I had that before, but I removed it for some reason............. Thanks Mike!
@MartinNordström Glad I could help! :)
3

You're basically trying to iterate over undefined/null object. Good practice is to set arrays initial state in redux store to an empty array. Having that you don't have to add additional checks in your component to check if array actually exists. Array.prototype.map just won't iterate over an empty array and won't render anything. Make sure you set initial state of customer.data to an empty array in your reducer.

1 Comment

I have this in my reducer: export function customer(state = [], action)
2

If you fetch data from API, you have no data in initial rendering, so you should try something like this:

    {this.props.customer.data ? this.props.customer.data.map(customers => 
      <p>
        {customers.name}
      </p>) : null}

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.