Home > Mobile >  React: async/await function returns undefined then value I want
React: async/await function returns undefined then value I want

Time:12-30

I have this async function:

Which returns undefined on the first render and then the data from the fetch:

const [
  MessageListDataProvider,
  useMessageListData
] = constate(() => {
  const [messagePath, useMessagePath] = useState(api.UNRESOLVED_MESSAGES_PATH)
  const getMessagePath = (newPath) => {
    useMessagePath(newPath)
  }
  const [messages, setMessages] = useState({})

  const {
    value,
    loading,
    error,
    retry: refresh
  } = useAsyncRetry(async () => {
    if (!messages[messagePath] && !messages.links ) {
      return await api.fetchAllMessages(messagePath).then(async (data) => {
        const localData = await data
        let localMessages = { ...messages }
        localMessages = { ...localMessages, [messagePath] : localData.messages }
        localMessages = { ...localMessages, ['links'] : localData.links }
        console.log('localMessages', localMessages)
        return await localMessages
      })
    }
  }, [messagePath])
  
  console.log('value', value)

  return {
    getMessagePath,
    value,
    loading,
    error,
    refresh
  }
})

value undefined

MessageListView.jsx:23 value 23 undefined

MessageListDataProvider.js:34 value undefined

MessageListView.jsx:23 value 23 undefined

MessageListDataProvider.js:28 localMessages {/messages?status=Unresolved&limit=100&offset=0: Array(64), links: {…}}

MessageListDataProvider.js:34 value {/messages?status=Unresolved&limit=100&offset=0: Array(64), links: {…}}

MessageListView.jsx:23 value 23 {/messages?status=Unresolved&limit=100&offset=0: Array(64), links: {…}}

How can I prevent the return value from being undefined as it's causing me not to get any day in my <MessageListView /> component.

CodePudding user response:

You need a loading state. Initiate state to loading, and then inside MessageListView, display a loader when the value is undefined. Or conditionally do not display MessageListView at all, but a loader instead when state is set to loading. Also you might want to wrap the async call into a react useEffect callback, as it's a side-effect.

CodePudding user response:

The async function will return undefined when its "if" statement fails - you should probably be handling that case better:

async () => {
    if (!messages[messagePath] && !messages.links ) {
        ...
    } else {
        return { /* something that's not undefined! */ }
    }
}
  • Related