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?
CodePudding user response:
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.
CodePudding user response:
I think you're trying to print an object to HTML. {anonymousObject}
doesn't work. You should use {JSON.stringify(anonymousObject)}
instead.