Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


    Automatically Send Changes to the Server by Using onSnapshot


    Let's make sure our changes get persisted. We will use the window.fetch api to store our changes in the json-server. And onSnapshot to do this automatically



    Become a Member to view code

    You must be a Pro Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    orLog In




    So far, we have been able to load data and re-load data, but we can't save data yet. To fix that, we want to be able to save an individual user.

    Now we can simply create a new action on our user which is called, "Save." This again is an action inaudible process, so let's again use a flow. We use the effects API to store and to call a style user under its own ID.

    For that we use a boot call. We send our body as JSON, and the contents of the body is simply the signification of our current state. Let's make sure that we also are handling it properly, so the yield has returns. We make sure to get any exceptions.

    Now, the interesting question is, when should we call this save action? There are few cases where we obviously need to call it. If I add a new item, I should call save. If I modify one, I should call save as well.

    If I either save it or I simply remove it, it should be saved. Also, if I click the suggestions button which adds a few items, it should be saved. Also, if it's rather a lot, it should be saved.

    We have at least five cases where somehow we change the user. Then we want to call the save method.

    If I can find five cases in a few seconds, then it's probably pretty easy to forget one as well. We can also solve this more generically. We can bring in our lifecycle hooks again. What did we say? After create, we start listening to the snapshots produced by this instance.

    Whenever the snapshot changes, we called that inaudible save. Whenever the instances of JSON representation changes, we make sure we send it to the server.

    Let's quickly try that. We don't want a soccer ball any more. Instead, we want some chocolate letter.

    I make a few invitations. I also want some suggestions. This is a double entry.

    If I now reload a bit, I check my status inaudible on the server.