0

I have a Client component that contains a ClientInfo and ClientForm component. Client has a client in its data and passes it to both the form and info as a prop. Inside the ClientForm component I have a method to handle the backend. Now when I try and do this:

axios.put(url, body).then(res => {
  this.client = res.data
})

I get the error message about directly mutating props and how I shouldn't do it. Now currently I do this:

axios.put(url, body).then(res => {
  Object.keys(res.data).forEach((i) => {
    if(this.client[i] != res.data[i]){
      this.client[i] = res.data[i]
    }
  })
})

Which seems... well kind of sub-optimal.

Is there a better way to handle updating the client object from the ClientForm so that the ClientInfo component gets the new info?

Killerpixler
  • 4,200
  • 11
  • 42
  • 82
  • thanks guys. Yes this means this is absolutely a duplicate of the other questions, I just didn't know this $emit was a thing :) – Killerpixler Feb 15 '18 at 00:57

1 Answers1

3

You could emit a custom event with the new data:

axios.put(url, body).then(res => {
  this.$emit('client', res.data)
})

...and then react to that event in your Client parent component to update its state:

<ClientForm @client='(data) => client = data' />

I hope this helps.

Steve Holgado
  • 11,508
  • 3
  • 24
  • 32
  • See also [the `.sync` modifier](https://vuejs.org/v2/guide/components.html#sync-Modifier) – Roy J Feb 14 '18 at 19:58