6 JavaScript Projects by Michaela Lehr & Michael Wanyoike & Darren Jones & Adam Janes

6 JavaScript Projects by Michaela Lehr & Michael Wanyoike & Darren Jones & Adam Janes

Author:Michaela Lehr & Michael Wanyoike & Darren Jones & Adam Janes [Lehr, Michaela]
Language: eng
Format: epub
Publisher: SitePoint
Published: 2018-05-30T23:00:00+00:00


Actions

Actions are functions used to update the state object. They’re written in a particular form that returns another, curried function that accepts the current state and returns an updated, partial state object. This is partly stylistic, but also ensures that the state object remains immutable. A completely new state object is created by merging the results of an action with the previous state. This will then result in the view function being called and the HTML being updated.

The example below shows how to create an action called changeName(). This function accepts an argument called name and returns a curried function that’s used to update the name property in the state object with this new name.

const actions = { changeName: name => state => ({name: name}) };

To see this action, we can create a button in the view and use an onclick event handler to call the action, with an argument of “Batman”. To do this, update the view function to the following:

const view = (state, actions) => ( <div> <Hello name={state.name} /> <button onclick={() => actions.changeName('Batman')}>I'm Batman</button> </div> );

Now try clicking on the button and watch the name change!

You can see a live example here.



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.