Skip to content

Error setting state for the empty array #11

@mcshakes

Description

@mcshakes

Actual Error:
Objects are not valid as a React child (found: object with keys {_id, title, description, date, price, creator}). If you meant to render a collection of children, use an array instead.

Screen Shot 2019-07-19 at 2 07 07 PM

Following the instructions, I initialize the state of events to an empty array above the constructor within Events.js.

After the componentDidMount, fetchAllEvents is called and the events (all coming in as an array) apparently don't like to be replacing the initial empty array. Relevant code below


import Modal from "../components/modals/Modal";
import Backdrop from "./backdrop/Backdrop";
import AuthContext from "../context/auth-context";
import "./Events.css";


class EventsPage extends React.Component {
	state = {
		creatingStatus: false,
		events: []
		
	};

	static contextType = AuthContext;

	constructor(props) {
		super(props);

		this.state = {
			title: "",
			price: "",
			date: "",
			description: "",
		}
	}

	componentDidMount() {
		this.fetchAllEvents();
	}

	createEventHandler = () => {
		this.setState({ creatingStatus: true });
	}

	cancelEventCreation = () => {
		this.setState({ creatingStatus: false });	
	};

	handleChange = (event) => {
		this.setState({
			[event.target.name]: event.target.value
		})
	};

	fetchAllEvents = () => {
		let requestBody = {
			query: `
				query {
					events {
						_id
						title
						description
						date
						price
						creator {
							_id
							email
						}
					}
				}
			`
		}
		
		fetch("http://localhost:8080/graphql", {
			method: "POST",
			body: JSON.stringify(requestBody),
			headers: {
				"Content-Type": "application/json"

			}
		})
		.then(res => {
			if (res.status !== 200 && res.status !== 201) {
				throw new Error("Failed!");
			}
			return res.json();
		})
		.then(resData => {
			const events = resData.data.events;
			
			this.setState({ events: events });
		})
		.catch(err => {
			console.log(err);
		})
	}

	render() {
		console.log("RENDER STATE =>", this.state)

		const allEvents = this.state.events;

		const eventList = allEvents && allEvents.map(event => {
			return <li key={event._id} className="events__list-item">{event.title}</li>					
		})

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions