Master Oogway
Master Oogway

Reputation: 63

ReactJS & Javascript: Getting "Error: Objects are not valid as a React child" when trying to set JSON Objects into a state hook

Overview: I have two components: ComponentA and ComponentB, I would like to make a POST request to my API and store the returned JSON string into a useState hook, and then pass that state to componentB. In ComponentB I would like to use the .map() function to iterate through the prop's contents.

API response JSON Data Structure: [{object: 1, name: 'bob'},{object: 2, name: 'joe'}...]

Here is my state hook definition:

const [data, setData] = useState([]);

My API call:

  const handleSubmit = () => {
    console.log("Function Called");
    fetch("/post", {
      method: "POST",
      mode: "cors",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify(formik.values),
    })
      .then((response) => response.json())
      .then((res) => {
        console.log(typeof res);
        setData(res);
      })
      .catch((err) => {
        console.log(err);
      });
  };

and my ComponentB .map() function

      <tbody>
        {props.responses.length > 0 ? (
          props.responses.map((response) => (
            <tr
              class={
                tableRow === "" ? (tableRow = "table-primary") : (tableRow = "")
              }
            >
              <td>{response.object}</td>
              <td>{response.name}</td>
            </tr>
          ))
        ) : (
          <tr></tr>
        )}
      </tbody>

whenever I make the API call I get this error:

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

is it possible to set the response in the state as a JSON object and pass it to ComponentB? If so what am I doing wrong?

Or do I need to pass it off as a string and then JSON.parse() in ComponentB? (the only problem with this is that JS throws a cors error, why is that?

Upvotes: 2

Views: 240

Answers (2)

Aleksandr Smyshliaev
Aleksandr Smyshliaev

Reputation: 420

Error tell you that you try to put whole JS object in JSX markup, you can't do that. Just look what you getting from API and how you trying to display it.

Upvotes: 1

Master Oogway
Master Oogway

Reputation: 63

I ended up moving component B inside Component A. The reason, I believe is that when the browser requested data from the backend, the browser wants to keep the data within its domain, so it throws a cors error when it passes the data from the browser to Component B which would be inside the virtual DOM, not yet rendered in the browser. So it's not an error thrown by the interaction of the components but by the interaction of the browser and the ReactJS server. The way to go about this is not to pass the entire state, but instead to pass individual props.

Upvotes: 0

Related Questions