0

I need to set data from the backend to an object using react hook. The data from the backend cannot be the same structure always, so need to treat that as an Anonymous Object.

import axios from "axios";

function AppNew() {
  const [anonymousObject, setAnonymousObject] = useState({});

  useEffect(() => {
    const fetchData = async () => {
      const result = await axios("https://example.com/GetData");
      setAnonymousObject(result.data);
    };
    fetchData();
  }, []);

  return <div> {anonymousObject} </div>;
}
export default AppNew;

It ends up with the error

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

Any idea how to handle this?

Sukesh Chand
  • 2,339
  • 2
  • 21
  • 29
  • what is the structure of your object? what are you trying to do with it? please update your answer. – szaman Mar 30 '22 at 11:03
  • 1
    currently you're trying to just render an object in the DOM, which react doesn't allow you to do. – szaman Mar 30 '22 at 11:03
  • 1
    if perhaps you want to render the object's JSON structure, you can use `
    {JSON.stringify(anonymousObject)}
    `
    – Nsevens Mar 30 '22 at 11:04
  • Does this answer your question? [Invariant Violation: Objects are not valid as a React child](https://stackoverflow.com/questions/33117449/invariant-violation-objects-are-not-valid-as-a-react-child) – David Mar 30 '22 at 11:08
  • @szaman the structure of the object is anonymous, it can very. I can pass the data from the backend as a json string and temporary fix the issue, but it will be good if there any other solution exists. – Sukesh Chand Mar 30 '22 at 12:30
  • @Nsevens What you said is correct! I was thinking something wrong with the useState(), it was not. The problem was in the UI rendering side. The react cannot render the object directly on the UI. ```{JSON.stringify(anonymousObject)}``` this fixes the issue – Sukesh Chand Mar 30 '22 at 13:24

2 Answers2

1

I think you're trying to print an object to HTML. {anonymousObject} doesn't work. You should use {JSON.stringify(anonymousObject)} instead.

Jithesh Kt
  • 2,023
  • 6
  • 32
  • 48
0

Well you can't mount any object in render. What you should do instead is to create a function which takes your object and return a component. Some king of a mapper function which takes some values from you object and create texts or whatever you want with them.

Pasca Marius
  • 111
  • 2