itman312
itman312

Reputation: 11

Using map function on array from state

The map function isn't working when used on an array that's retrieved from the state property.

Here is how my state is defined in the class:

  state = {
    isLoading: true,
    groups: []
  };

Inside my render method, I try to use the groups array like so:

const groups = this.state.groups;

Inside of my return statement in the render method, I call groups.map()

However, I get an error saying that map() is an invalid function for groups.

However, when I set the groups array outside of state entirely like so:

   let groups = [];
   groups = this.state.groups;

The map function works just fine. So it seems that this.state.groups isn't actually accessing the groups array in state. How can I access the array from state?

Here is my full file:

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';

class App extends Component {
  state = {
    isLoading: true,
    groups: []
  };

  async componentDidMount() {
    //const response = await fetch('/api/groups');
    //const body = await response.json();
    const testJson = '{"id" : "1", "name" : "Denver"}';
    const body = JSON.parse(testJson);
    this.setState({ groups: body, isLoading: false });
  }

  render() {
    const {groups, isLoading} = this.state;

    if (isLoading) {
      return <p>Loading...</p>;
    }

    return (
      <div className="App">
        <header className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <div className="App-intro">
            <h2>JUG List</h2>
            {groups.map(group =>
              <div key={group.id}>
                {group.name}
              </div>
            )}
          </div>
        </header>
      </div>
    );
  }
}

export default App;

Upvotes: 0

Views: 72

Answers (1)

Zac Anger
Zac Anger

Reputation: 7747

Your test json is parsed into an object, which you can't map over (at least, not without a third-party library to provide a map that works for objects, like lodash's _.map). If you change that to const testJson = '[{"id" : "1", "name" : "Denver"}]' it should work.

Upvotes: 1

Related Questions