Search code examples
reactjsreact-statereact-state-management

React Component Not Being Populated even after updating state and executing forEach


I want to fetch memes from the imgflip meme API, and even though I get to see the HTTP response in my console, the DOM is not getting populated, I tried everything.

export default class MemesContainer extends Component {
  constructor() {
    super();
    this.state = {
      memes: [],
    };
  }
  async componentDidMount() {
    let req = await fetch("https://api.imgflip.com/get_memes");
    let res = await req.json();
    console.log(res.data.memes);
    await this.setState({ memes: res.data.memes });
  }
  render() {
    return (
      <div className="container d-flex justify-content-center flex-wrap">
        {this.state.memes.map((e) => {
          <div className="card m-3" style={{ width: "18" + "rem" }}>
            <img src={e.url} className="card-img-top" alt="..." />
            <div className="card-body">
              <h5 className="card-title">{e.name}</h5>
            </div>
          </div>;
        })}
      </div>
    );
  }
}

Solution

  • ForEach Doesn't return anything, it just executes the code. At this point you should use Array.map as it is meant to loop through array and transform it's values and return them.

    export default class MemesContainer extends Component {
      constructor() {
        super();
        this.state = {
          memes: [],
        };
      }
      async componentDidMount() {
        let req = await fetch("https://api.imgflip.com/get_memes");
        let res = await req.json();
        console.log(res.data.memes);
        await this.setState({ memes: res.data.memes });
      }
      render() {
        return (
          <div className="container d-flex justify-content-center flex-wrap">
            {this.state.memes.map((e) => {
              return (
              <div className="card m-3" style={{ width: "18" + "rem" }}>
                <img src={e.url} className="card-img-top" alt="..." />
                <div className="card-body">
                  <h5 className="card-title">{e.name}</h5>
                </div>
              </div>
            )
            })}
          </div>
        );
      }
    }