Skip to content
Advertisement

Why I am getting cross origin error in React?

I am quite new in React. I have build an event scheduler web app but it’s only working in my browser if I try it to different browsers or someone else system it gives me this error:

A cross-origin error was thrown. React doesn’t have access to the actual error object in development.

I am trying to figure out but all I can understood it’s happening because I am giving default values in state if local storage in undefined. Here is my complete code.

This is the component that is getting the error:

import React from "react";
import { Container, Row, Table } from "react-bootstrap";
import EventModal from "./EventModalButton";

class EventList extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      title: "",
      eventtype: "",
      time: ""
    };
  }

  componentDidMount() {
    const defaultData = {
      title: "AI",
      eventtype: "Workshop",
      time: "02:00PM"
    };
    const eventData = JSON.parse(localStorage.getItem("Data") || defaultData);
    this.setState({
      title: eventData.title,
      eventtype: eventData.eventtype,
      time: eventData.time
    });
  }

  render() {
    return (
      <Container fluid="md">
        <Table striped bordered hover>
          <thead>
            <tr>
              <th>Title</th>
              <th>Type</th>
              <th>Time</th>
              <th>Date</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td>{this.state.title}</td>
              <td>{this.state.eventtype}</td>
              <td>{this.state.time}</td>
              <td>Monday, 31/08/2020</td>
            </tr>
          </tbody>
        </Table>

        <Container className="row" />
        <Row className="justify-content-center">
          <EventModal />
        </Row>
      </Container>
    );
  }
}
export default EventList;

Advertisement

Answer

You’re trying to parse an object. JSON.parse expects a JSON but you’re passing an object.

You could check the sandbox here

 componentDidMount() {
    const defaultData = {
      title: "AI",
      eventtype: "Workshop",
      time: "02:00PM"
    };
    
    // JSON.parse throws an error when parsing the object.
    const eventData = JSON.parse(localStorage.getItem("Data")) || defaultData;
    this.setState({
      title: eventData.title,
      eventtype: eventData.eventtype,
      time: eventData.time
    });
  }
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement