All files / src GreetingController.js

47.62% Statements 10/21
100% Branches 2/2
54.55% Functions 6/11
50% Lines 10/20
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73              1x 1x       5x 5x       1x               2x 2x             2x       2x 2x                                                                    
import React from 'react';
 
import {loadFromServer, saveToServer} from './backend';
 
import GreetingMaster from './GreetingMaster';
import GreetingDetail from './GreetingDetail';
 
const MODE_MASTER = 'MODE_MASTER';
const MODE_DETAIL = 'MODE_DETAIL';
 
export default class GreetingController extends React.Component {
    render() {
        const {mode, greetings} = this.state;
        return (
            <div>
                {mode === MODE_MASTER ?
                    <GreetingMaster greetings={greetings}
                                    onAdd={() => this.setState({mode: MODE_DETAIL})}
                    /> :
                    <GreetingDetail onAdd={(greeting) => this.saveGreeting(greeting)}/>
                }
            </div>);
    }
 
    constructor(props) {
        super(props);
        this.state = {
            greetings: [],
            mode: MODE_MASTER
        };
    }
 
    componentDidMount() {
        this.loadGreetings();
    }
 
    loadGreetings() {
        loadFromServer(
            greetings => this.setState({greetings}),
            err => console.error('LOADING GREETINGS FAILED:', err)
        );
    }
 
 
    saveGreeting(greetingToBeAdded) {
        const _addNewGreeting = serverResponse => {
            // the server responded with the id of the new Greeting
            const newGreetingId = serverResponse.id;
            // create a new Greeting object that contains the received id
            // (create a new object for immutability)
            const newGreeting = {...greetingToBeAdded, id: newGreetingId};
            // add the new greetings to the list of all greetings
            // (create a new array for immutability)
            const newGreetings = [...this.state.greetings, newGreeting];
 
            // set the new list of greetings as our new state
            // also set 'MODE_MASTER' to make sure the master-View is
            // displayed now
            this.setState({
                greetings: newGreetings,
                mode: MODE_MASTER
            });
 
            return newGreeting;
        };
 
        const _reportError = err => console.error('COULD NOT SAVE GREETING: ', err);
 
        saveToServer(greetingToBeAdded, _addNewGreeting, _reportError);
    }
}