0

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;

1 Answer 1

1

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.

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

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.