Save 45% for a limited time.

Get access to all courses and lessons on egghead today.

Autoplay

    Automatically Send Changes to the Server by Using onSnapshot

    Michel WeststrateMichel Weststrate

    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

    reactReact
    ^16.0.0
    mobxMobX
    ^3.0.0
    Code

    Code

    Become a Member to view code

    You must be a 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
    Transcript

    Transcript

    00:00 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.

    00:11 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.

    00:30 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.

    00:51 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.

    01:05 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.

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

    01:25 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.

    01:43 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.

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

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

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

    Discuss

    Discuss