0

I am very new to the coding world. I am creating a meme generator and fetching data from the api. The below is part of the code, there is a const {memes} to store the data fetched from api, but why do I need it? Why can't I put it like this --> this.setState({allMemeImg: response.data})

    componentDidMount(){
        fetch("https://api.imgflip.com/get_memes")
        .then (response => response.json())
        .then (response => {   
            const {memes} = response.data 
            this.setState({allMemeImg: memes})
                })
    }
Betty
  • 35
  • 4
  • 3
    That's called a [destructuring assignment](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#Object_destructuring). It's the same as doing `const memes = response.data.memes`. Without it, you'd do `this.setState({ allMemeImg: response.data.memes })`. It's not required - it's just syntactic sugar for your convenience. – cbr Jul 02 '20 at 14:23
  • You can. just ```setState({allMemeImg: resopnse?.data?.memes})``` – cybercoder Jul 02 '20 at 14:24
  • @cybercoder I'd argue that `?.` changes the semantics a little bit :) – cbr Jul 02 '20 at 14:25
  • Does this answer your question? [Javascript object bracket notation ({ Navigation } =) on left side of assign](https://stackoverflow.com/questions/26999820/javascript-object-bracket-notation-navigation-on-left-side-of-assign) – jonrsharpe Jul 02 '20 at 14:25
  • @cybercoder the `?` do not change anything here actually. – Slavian Jul 02 '20 at 14:25
  • Question Mark operator is needed to prevent error when there's no nested key or object, and returns ```undefined``` instead of error. – cybercoder Jul 02 '20 at 14:27

3 Answers3

0

the line const {memes} = response.data is using destructuring syntax to assign response.data.memes to a constant memes. it is equivalent to saying const memes = response.data.memes. you could skip it and do this.setState({allMemeImg: response.data.memes})

Ethan Lipkind
  • 1,126
  • 2
  • 7
0

Your API returns an object with more parameters where memes is one of them. With this syntax const {memes} = response.data you extract only the memes property. You can skip this and use directly this.setState({allMemeImg: respone.data.memes})

Dani
  • 447
  • 4
  • 9
0
const { memes } = response.data;

is the same as

const memes = response.data.memes;

You could even do this:

const { data: { memes }} = response;
Neskews
  • 554
  • 1
  • 6
  • 18