Should a spread operator be used when updating an object with svelte/store update method?
Asked Answered
A

1

6

I'm creating a store that uses an object to store my data.

I can update the store using the spread operator, but I can also update it without the spread operator.

Is Svelte like React where I should use the spread operator to create a new object prior to updating the state of the object so I'm not mutating the original object?

withSpreadOperator() or withoutSpreadOperator()... that is the question.

//stores.js

import { writable } from "svelte/store";

export const counts = writable({ n: 0 });
//App.js

<script>
  import { count } from "./stores.js";

  function withSpreadOperator() {
    count.update(o => {
      let x = { ...o };
      x.n++;
      return x;
    });
  }

  function withoutSpreadOperator() {
    count.update(o => {
      o.n++;
      return o;
    });
  }
</script>

<h1>The count is {$count.n}</h1>
<button on:click="{withSpreadOperator}">+</button>
<button on:click="{withoutSpreadOperator}">+</button>
Amiens answered 3/12, 2019 at 21:31 Comment(0)
G
12

You can do either, Svelte doesn't mind. It's really just down to which style you prefer.

Gruesome answered 4/12, 2019 at 1:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.