I get this error because I’m trying to use symbolArray in my jsx can anyone explain to me how to fix this?
Uncaught Invariant Violation: Objects are not valid as a React child (found: [object Promise]). If you meant to render a collection of children, use an array instead.
const getSymbolArray = async () => {
let poloniex = new ccxt.poloniex();
poloniex.id, await poloniex.loadMarkets();
symbolArray = poloniex.symbols;
};
const symbolList = getSymbolArray().then(() => {
symbolArray.map(symbolitem => {
return <option>{symbolitem}</option>;
});
});
return ( {symboList} )
In my return, I call it with {symboList}
It’s because it’s trying to render an unresolved promise, which isn’t a thing you can render. The thing you want doesn’t exist at the point in time you want to render it: getSymbolArray
is async, so the return value is, practically, either going to be the array you want, or a promise saying you might get that array. When symbolList
runs, it’s the latter.
Normally the simplest way is to rely on the fact the React components rerender when props change. Verbosely:
const SymbolList = ({symbolArray}) => {
if (!symbolArray) {
return null;
} else {
return (
<>
{symbolArray.map(symbolitem => <option>{symbolitem}</option>)}
</>
);
}
});
Then in the parent component, have a key in state for the symbolArray
, run the async fetch function in componentDidMount()
and populate that piece of state with the result. In the render
, just use that component. It doesn’t have to be separated out, you can inline it like you are doing at the minute, it just generally makes things a bit easier to grok and debug if you have it separated.
Hm the component I need this is a functional component it is giving me a weird syntax highlighting using this <> </>
That’s your syntax highlighting not being set up correctly for newer versions of react. It’s the same as this, which is a little bit more verbose but should kill the errors:
<React.Fragment>
{/*Your stuff*/}
</React.Fragment>
Basically, a JSX component needs a single root element, but with a map of options you have something like
option
option
option
And Fragment is like an empty wrapper to avoid that issue:
Fragment
option
option
option
Thanks, I will check it out and learn more about how to setup my project correctly for the newest version of react. I think it has something todo with webpack/babel I swiched recently to to newest versions.