javascriptcontentfulcontentful-management

How to update a single field in a Contentful entry?


Need help updating a field in a CF entry. It is a dropdown field without a default value.

I tried to do that by getting the entry from the CF environment, setting the corresponding field and updating it like this:

        client.getSpace(spaceId)
        .then((space) => {space.getEnvironment(environment)
            .then((environment) => {environment.getEntry('1234567890')
                .then((entry) => {
                    entry.fields = {
                        state: {
                            'en-US': 'Arizona'
                        }
                    }
                    return entry.update()
                })
            })
        })

By doing so, the state value gets updated, but the other existing field values are deleted.

The Contentful documentation for content update states the same here: https://www.contentful.com/developers/docs/references/content-management-api/#/introduction/updating-content, but I cannot find a way to implement their suggestion.

How do I update the state value without losing all the other fields?


Solution

  • When you do

    entry.fields = {
      state: {
        'en-US': 'Arizona'
      }
    }
    

    You replace the whole fields object by the new one containing only one key: state.
    Instead of setting entry.fields, you should set entry.fields.state

    Example:

    client.getSpace(spaceId)
        .then(space => space.getEnvironment(environment))
        .then(environment => environment.getEntry('1234567890'))
        .then(entry => {
            entry.fields.state = {
                'en-US': 'Arizona'
            }
            return entry.update()
        });
    

    Also: I changed the way you use .then(). One of the benefits of Promises is that you don't have to nest callbacks. Here you are nesting callbacks. You can chain .then() calls to make your code more readable, as I did in the sample above. See: Aren't promises just callbacks?