Federico Zacayan

Software Devloper.

React

Wellcome to React Section

There was upnon a time an api RESTful built with React. This aplication consisted in two functions wrote in TypeScript, she was App.js and he was User.js. She was very happy. Every response she got was shared with her husband. He, as a good man, always rendered the data received from his wife.

App.js had a lover, but User.js never realize that. The third part was an elegant server who serve all the request he got of every single innocent App.js he met.

The poor User.js was a good man. But he was not smart. He never handled the status of his relationship and always obey the instructions App.js gave to him.

This story start in the following way...

Chapter 1: Getting fake users from server.

Create react project

npx create-react-app react-tutorial

Go to the folder

cd react-tutorial

Overwrite the src/App.js file

import React, { useState, useEffect } from "react";
import User from './User'

function App() {

    const [info, setInfo] = useState();

    useEffect(() => { //same functionality of componentDidMount()
        fetch('http://jsonplaceholder.typicode.com/users')
        .then(res => res.json())
        .then((data) => {
            console.log(data);
            setInfo(data)
        })
        .catch(console.log)
    }, []);

    if(typeof info === 'undefined'){
        return (<div>Loading...</div>)
    } else {
        return (<div>
            {info.map((contact) => (
                <User key={contact.id} contact={contact}></User>
            ))}
            </div>)
    }
}

export default App;

Create src/User.js

import React from "react";

const User = ({contact}) => {
    return (<div>
                <span>Email: {contact.email}</span><br/>
                <span>Name: {contact.name}</span><br/>
                <span>Phone: {contact.phone}</span>
                <hr/>
            </div>);
}

export default User;

Run local server

npm start

Check it out in the browser

http://localhost:3000/

Chapter 2: Delete Users.

Add deleting and deleteUser inner functions to src/App.js

    ...
    const deleting = (id) =>{
        let tmp  = info.filter((a) => {
            return a.id !== id;
        })
        setInfo(tmp);
    }

    const deleleUser = (id) => {
        fetch('https://jsonplaceholder.typicode.com/posts/'+id, {
          method: 'DELETE'
        })
        .then(() => {
            deleting(id);
        })
    }
    ...

Modify the return of src/App.js adding prop deleleUser.

<User key={contact.id} contact={contact} deleleUser={deleleUser} ></User>

Add a button and an inner function to add the id as a parameter in deleleUser method in src/User.js

import React from "react";

const User = ({contact, deleleUser}) => {
    const drop = () => {
        deleleUser(contact.id)
    }
    return (<div>
                <span>Email: {contact.email}</span><br/>
                <span>Name: {contact.name}</span><br/>
                <span>Phone: {contact.phone}</span>
                <input type="button" onClick={drop} value="Delete"/>
                <hr/>
            </div>);
}

export default User;

Test the application.


Chapter 3: Update Users.

Add the following methods for update in src/App.js and send updateUser function as a prop.

    ...
    const updating = (post) =>{
        console.log("Updating "+post.id+" done!");
    }

    const updateUser = (post) => {
        console.log("Updating "+post.id);
        fetch('https://jsonplaceholder.typicode.com/posts/'+post.id, {
        method: 'PUT',
        body: JSON.stringify(post),
            headers: {
              "Content-type": "application/json; charset=UTF-8"
            }
        })
        .then(response => response.json())
        .then(json => updating(json))
    }
    ...

    <User key={contact.id} contact={contact} deleleUser={deleleUser} updateUser={updateUser}></User>

In order to avoid UX complexity required we will implement the editable attribute in src/User.js and we will set some methods for data updating when blur happen.

import React from "react";

const User = ({contact, deleleUser, updateUser}) => {

    const drop = () => {
        deleleUser(contact.id)
    }

    const updateMail = (e) => {
        contact.email = e.target.innerHTML;
        updateUser(contact);
    }

    const updateName = (e) => {
        contact.name = e.target.innerHTML;
        updateUser(contact);
    }

    const updatePhone = (e) => {
        contact.phone = e.target.innerHTML;
        updateUser(contact);
    }

    return (<div>
                <span>Email: <span contenteditable="true" onBlur={updateMail}>{contact.email}</span></span><br/>
                <span>Name: <span contenteditable="true" onBlur={updateName}>{contact.name}</span></span><br/>
                <span>Phone: <span contenteditable="true" onBlur={updatePhone}>{contact.phone}</span></span>
                <input type="button" onClick={drop} value="Delete"/>
                <hr/>
            </div>);
}

export default User;

Test the application again.


Chapter 4: Add new User.

Finally, we implement create method adding a button in src\App.js.

    if(typeof info === 'undefined'){
        return (<div>Loading...</div>)
    } else {
        return (<div>
            {info.map((contact) => (
                <User key={contact.id} contact={contact} deleleUser={deleleUser} updateUser={updateUser}></User>
            ))}
            <input type="button" onClick={create} value="Create new  User"/>
            </div>)
    }

And set the method create.

    const create = () => {
        fetch('https://jsonplaceholder.typicode.com/posts', {
            method: 'POST',
            body: JSON.stringify({
                name: 'Jhon Doe',
                email: 'bar@email.com',
                phone: '444-555'
            }),
            headers: {
                "Content-type": "application/json; charset=UTF-8"
            }
        })
        .then(response => response.json())
        .then(json => {
            console.log(json);
            setInfo([...info, json]);
        })
    }

The final result is src\App.js.

import React, { useState, useEffect } from "react";
import User from './User'

function App() {

    const [info, setInfo] = useState();

    useEffect(() => { //same functionality of componentDidMount()
        fetch('http://jsonplaceholder.typicode.com/users')
        .then(res => res.json())
        .then((data) => {
            console.log(data);
            setInfo(data)
        })
        .catch(console.log)
    }, []);

    const deleting = (id) =>{
        let tmp  = info.filter((a) => {
            return a.id !== id;
        })
        setInfo(tmp);
    }

    const deleleUser = (id) => {
        console.log("deleting "+id);
            fetch('https://jsonplaceholder.typicode.com/posts/'+id, {
          method: 'DELETE'
        })
        .then(() => {
            deleting(id);
        })
    }

    const updating = (post) =>{
        console.log("Updating "+post.id+" done!");
    }

    const updateUser = (post) => {
        console.log("Updating "+post.id);
        fetch('https://jsonplaceholder.typicode.com/posts/'+post.id, {
        method: 'PUT',
        body: JSON.stringify(post),
            headers: {
              "Content-type": "application/json; charset=UTF-8"
            }
        })
        .then(response => response.json())
        .then(json => updating(json))
    }

    const create = () => {
        fetch('https://jsonplaceholder.typicode.com/posts', {
            method: 'POST',
            body: JSON.stringify({
                name: 'Jhon Doe',
                email: 'bar@email.com',
                phone: '444-555'
            }),
            headers: {
                "Content-type": "application/json; charset=UTF-8"
            }
        })
        .then(response => response.json())
        .then(json => {
            setInfo([...info, json]);
        })
    }

    if(typeof info === 'undefined'){
        return (<div>Loading...</div>)
    } else {
        return (<div>
            {info.map((contact) => (
                <User key={contact.id} contact={contact} deleleUser={deleleUser} updateUser={updateUser}></User>
            ))}
            <input type="button" onClick={create} value="Create new  User"/>
            </div>)
    }
}

export default App;

And src\User.js.

import React from "react";

const User = ({contact, deleleUser, updateUser}) => {

    const drop = () => {
        deleleUser(contact.id)
    }

    const updateName = (e) => {
        contact.name = e.target.innerHTML
        updateUser(contact)
    }

    const updateMail = (e) => {
        contact.email = e.target.innerHTML
        updateUser(contact)
    }

    const updatePhone = (e) => {
        contact.phone = e.target.innerHTML
        updateUser(contact)
    }

    return (<div>
                <span>Name: <span contenteditable="true" onBlur={updateName}>{contact.name}</span></span><br/>
                <span>Email: <span contenteditable="true" onBlur={updateMail}>{contact.email}</span></span><br/>
                <span>Phone: <span contenteditable="true" onBlur={updatePhone}>{contact.phone}</span></span>
                <input type="button" onClick={drop} value="Delete"/>
                <hr/>
            </div>);
}

export default User;