Error is as follows: TypeError: projects.map is not a function

234 views Asked by At

[enter image description here][1]

I was trying to connect my react frontend to my spring boot backend. I encountered this error. how to resolve this? *I am a react and javascript newbie and trying to build a new application. I tried the solution on another stack overflow but nothing seems to be working. * [1]: https://i.stack.imgur.com/vaxWI.png

import React, { Component } from "react";
import ProjectItem from "./Project/ProjectItem";
import CreateProjectButton from "./Project/CreateProjectButton";
import { connect } from "react-redux";
import { getProjects } from "../actions/projectActions";
import PropTypes from "prop-types";
import Projects from './Projects';

class Dashboard extends Component {
  constructor(props){
    super(props);
  }
  componentDidMount() {
    this.props.getProjects();
  }



 render() {
    const { projects } = this.props.project;

return (
  <div className="projects">
    <div className="container">
      <div className="row">
        <div className="col-md-12">
          <h1 className="display-4 text-center">Projects</h1>
          <br />
          <CreateProjectButton />
          <br />
          <hr />
          {projects.map((project) => (<ProjectItem key={project.id} project={project} ></ProjectItem>))}
        </div>
      </div>
    </div>
  </div>
);


 }
}

Dashboard.propTypes = {
  project: PropTypes.object.isRequired,
  getProjects: PropTypes.func.isRequired
};

const mapStateToProps = state => ({
  project: state.project
});

export default connect(
  mapStateToProps,
  { getProjects }
)(Dashboard);



 import React,{ useState } from 'react'
import ProjectItem from './Project/ProjectItem';

const Projects = (props) => {
    return(
        <div>
        {props.projects.map((project) => (<ProjectItem key={project.id} project={project} ></ProjectItem>))}
        </div>
    )
}

export default Projects;

//dispatch redux func

    export const getProjects = () => async dispatch => {
  const res = await axios.get("/api/projects");
  dispatch({
    type: GET_PROJECTS,
    payload: res.data
  });
};
2

There are 2 answers

0
Atefeh ghahremani far On

pay attention to projects props to be a array data to be able to loop over it(not null, undefined, object). and also you can use optional chaining operator: '?'

(projects?.data) 

Enabling optional chaining in a create-react-app:

How to enable optional chaining with Create React App and TypeScript

2
Idan On

Try to add the optional chaining operator: '?' before the dot notation:

projects?.map

instead of

projects.map