1

I am trying to render a component conditionally based off the value of AsyncStorage, but I am getting the above error. I even tried converting the object to an Array, but that did not work as well. Not sure what else to do.

 const test = async () => {
      const test = await ratingCountCompleted;
      let result = Object.values(test);
      result = result.toString();
      console.log(result);

      if(result > 1) {
        console.log('YUP');
        
        return (
          <InAppRating />
        )
      } else {
        console.log('NOPE')
      }
    }
AS10
  • 271
  • 1
  • 15

2 Answers2

1

currently trying to help you out with this over at: codesandbox, but having a weird interaction where async is causing the problem.

EDIT: I think I found the problem. The test function is asynchronous and returning a promise as indicated in the error: Objects are not valid as a React child (found: [object Promise]).

Solution:

const [resultState, setResultState] = useState(null);

const test = async () => {
    const test = await ratingCountCompleted;
    let result = Object.values(test);
    result = result.toString();
    console.log(result);

    if (result > 1) {
        console.log("YUP");

        return <Text>Hey</Text>;
    } else {
        console.log("NOPE");
        return null;
    }
};

// setResultState on load
useEffect(() => {
  test().then((component) => setResultState(component));
}, []);

return <View>{resultState}</View>;

We have to use useState for our initial component state, which is null. Then we populate it with useEffect, get the returned promise from test, and finally render it.

A second codesandbox to test it

Christian
  • 356
  • 1
  • 5
  • 14
  • Of course, I appreciate the help. I did updated the above to something I tried right after this. I tried converting the array to a string, but it didn't like that still go the error. – AS10 Apr 13 '21 at 03:52
  • No problem! I think I found the solution, let me know if that works. It looks a little janky, but I believe the useEffect route is always the most optimal in react-native. – Christian Apr 13 '21 at 04:26
  • 1
    yes this worked, I appreciate it! That was a very helpful answer – AS10 Apr 13 '21 at 04:43
1

You can use conditionals to render o not elements like in this demo. But you'll need some state to trigger re-rendering. I hope this will help you:

import "./styles.css";
import React from "react";
import { View, Text } from "react-native";

export default function App() {
  const [result, setResult] = React.useState(0);
  const ratingCountCompleted = async () => 2;

  const test = async () => {
    const rating = await ratingCountCompleted();
    setResult(rating);
  };

  React.useEffect(() => {
    test();
  }, []);

  return (
    <div className="App">
      {(result > 1 && (<Text>Yup</Text>)) || (<Text>Nope</Text>)}
    </div>
  );
}

Demo

Fuze-Mcsea
  • 81
  • 6