FabricioG
FabricioG

Reputation: 3310

Unable to display promise data inside a method in render

I realize I can't return objects in a react render but I'm having a problem figuring out how to do this.

Error message:

Invariant violation, objects are not valid as a React child error

My method:

displayListItemComponent = item => {

    return this.getConcernsDB(item.values)
    .then(returnedConcerns => {
        if(returnedConcerns.length) {
          returnedConcerns.forEach(el => {
            return(el.name);
          })
        }
      }
    )
}

Partial render:

<CollapseBody>
  { el.details.map(item => (
    this.displayListItemComponent(item)
  ))}
</CollapseBody>

Here I am trying to return el.name from displayListItemComponent I am attempting to return displayListItemComponent in my react render. My assumption was that by returning the function this.getConcernsDB that it would chain down and it would return el.name. How can I achieve this?

Upvotes: 0

Views: 56

Answers (2)

Max
Max

Reputation: 4739

Your method returns a Promise. Render should be synchronous and have no side effects (e.g. it should only return allowed values from props and state). Therefore you need to store your data in state, and render elements from state

Upvotes: 2

Moinul Hossain
Moinul Hossain

Reputation: 2206

You could do something like this. Also what does el.name contain?

displayListItemComponent =(props) => {
    const {item} = props;
    const [data, setData] = useState();

    useEffect(() => {
      // i see you did this.getConcernsDB. where is it coming from?
       getConcernsDB(item.values)
    .then(returnedConcerns => {

        setData(returnedConcerns.values(el => el.name))
    )

    }, [])

    if(!data) return <SomeLoadingSpinner />

    // now you have access to the names in `data` variable. Return whatever component you want using the `data`
  }

Upvotes: 0

Related Questions