0

I'm looking at a piece of code that I don't understand:

const { data: user } = await axios.get(`/api/user/${id}`);

What does the { data: user } part do? I've never seen an object get destructured and assigned to another variable. More confusingly, I'm testing it out live, and there doesn't seem to be a difference between { data: user } = ... and { user } = ....

What's going on? There's a prop const [user, setUser] = useState(null); earlier in the file, does that have anything to do with it?

hauslex
  • 36
  • 6
  • See the docs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment "Assigning to new variable names". As for your case with `user`, can you provide a [mcve]? – ggorlen Aug 11 '21 at 18:30
  • When destructuring an object, the name before the `:` is the property name _within the object you are destructuring_, the name after is _the variable that value will be saved into_. In this example, the `axios.get` call returns an object with a `data` property, which you are destructuring into a variable named `user`. The earlier `useState` call is irrelevant except that the destructuring is possibly shadowing the `user` variable (but we can't tell without knowing the scope each is declared in). – CRice Aug 11 '21 at 18:35

0 Answers0