Search code examples
react-nativevariableses6-promisereact-hookscontentful

React Hook setState not set on promise


I'm using the Contentful CMS JS SDK and the code below does not update my React Hook state. It's more of a promises combined with react hooks combined with React render issue - I believe. I understand that the promise sets the hook value when it is resolved at a later time, but by that time my component already rendered with the initial data (empty string), so if this is the case, how can I make my component re-render when the react hook state is set with the correct value from the promise, so that my Button displays it. Any help appreciated. Thanks

Problem lies within here.

...
import client from 'contentful'
  const [name, setName] = useState('')

  client.getEntry(data.fields.store.sys.id)
    .then(entry => setName(entry.fields.name))
    .catch(console.error)

  console.log('STORE URL', name) // name is not set
...
<Button title={name} /> // name still not set
....

Solution

  • I just tried your code and it seems to work for me. :)

    https://codesandbox.io/embed/react-hooks-demo-e4wgo

    I think you should use useEffect though as described in this article.