Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Error setting state for the empty array #11

Open
mcshakes opened this issue Jul 19, 2019 · 0 comments
Open

Error setting state for the empty array #11

mcshakes opened this issue Jul 19, 2019 · 0 comments

Comments

@mcshakes
Copy link

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>					
		})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant