Search code examples
ecmascript-6returnarrow-functions

Returning Object Literals from ES6 arrow function


I will be appreciated if someone explains why in updatedPosts we should return an object and inside an object we should return it again? why can we just do this peace of code instead =>

const updatedPosts = posts.map(data => { ...data, author : 'Leo' } )

class Blog extends Component {
    state = {
        post : []
    }
    componentDidMount(){
axios.get('https://jsonplaceholder.typicode.com/posts')
.then(response => {
    const posts = response.data.slice(0,3);
    const updatedPosts = posts.map(data =>{
        return {
            ...data,
            author : 'Leo'
        }

    })
    this.setState({post : updatedPosts})
    console.log(response)
})

Solution

  • This piece of code const updatedPosts = posts.map(data => { ...data, author : 'Leo' } ) is actually possible but you have to put parenthesis around the object which gives you

    const updatedPosts = posts.map(data => ({ ...data, author : 'Leo' }))

    You can find the explanation in the Returning Object Literals section of this documentation https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions