简体   繁体   中英

How can I set state in useMemo with an async function?

I am trying to fetch data during ComponentWillMount lifecycle in server side using useMemo()

  const [text, setText] = useState('hello')
  
  const fakeApiCall = new Promise(resolve => 'world')
  
  useMemo(async () => {
    const value = await fakeApiCall
    setText(value)
  }, [])

Doing this the value for text will still remain hello instead of world . Is it possible to achieve this? Why is this not working?

as you know, the await will be return a 'promise object', and after the response came out it will be replaced with 'promise value', all you need is a falge to detect whenever you got a success response.

your code will seems like

  const [text, setText] = useState('hello')
  
  const fakeApiCall = new Promise(resolve => 'world')
  
  const [flage,setFlag] = useState(false) //adding whatever your flag name

  useMemo(async () => {
    const response = await fakeApiCall

    if(response.Success) // you will check on response result
    {
     setText(value)
    }
  }, [])

or you can check on this Promise.resolve(valueOrPromiseItDoesntMatter).then

Practically, you can achieve all you need here with useState and useEffect :

  const [text, setText] = useState('hello')
  
  const fakeApiCall = new Promise(resolve => 'world')

  useEffect(() => {
    fakeApiCall()
      .then(response => { setText(response) })
  },[])

Note that you do not need to make the function within the useEffect hook async as it will resolve normally through typical promise flow.

As we have passed nothing into the dependency array, this hook will execute once on component mount and effectively memoise the response in the text variable.

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