AS10
AS10

Reputation: 271

objects are not valid as a react child when trying to render component based off of AsyncStorage React-Native

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')
      }
    }

Upvotes: 1

Views: 183

Answers (2)

Fuze-Mcsea
Fuze-Mcsea

Reputation: 91

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

Upvotes: 1

Christian
Christian

Reputation: 366

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

Upvotes: 1

Related Questions