简体   繁体   中英

React - Context Provider - Calling Async Function Inside Consumer Returns Nothing After Promise is resolved

I'm trying to call an async function from the provider and then show content based on the response but nothing is returned. Can someone please advise what am I doing wrong? Below is the code:

const App = () => {
  return (
    <>
      <Header />
      <UserConsumer>
        {
          ({getProfile}) => {
            getProfile.then(profile) => {
              return profile && (
                <h3>{profile.name}</h3>
              )
            }
          }
        }
      </UserConsumer>
    </>
  )
}

I can see getProfile returns a promise with profile data and even if I remove profile && nothing shows. I have used other functions the same way. getProfile is the only async function and not sure why am I having this issue.

Any ideas? Thanks

Suppose your UserConsumer 's rendering logic is something like this:

<div>{props.children({getProfile})}</div>

Since you are not returning anything in this function:

     ({getProfile}) => {
        getProfile.then(profile) => {
          return profile && ( // this is return value of then callback, not props.children
            <h3>{profile.name}</h3>
          )
        }
      }

Everytime React renders UserConsumer , the final JSX to be rendered is this:

    <div>{undefined}</div>

The main problem of your code, You are not supposed to do asynchronous operations in return sections of React Components.

If you need to render some UI based on server side data (like profile data), you need to fetch data in useEffect , then put the received data in some state , and use the state in return of the component.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM