react · http-app >npm install >npm start usman akram cui lahore 3

24
React CALLING BACKEND SERVICES

Upload: others

Post on 03-Jun-2020

18 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: React · http-app >npm install >npm start Usman Akram  CUI LAHORE 3

ReactCALLING BACKEND SERVICES

Page 2: React · http-app >npm install >npm start Usman Akram  CUI LAHORE 3

Code Basehttps://1drv.ms/f/s!AtGKdbMmNBGdg_MrgNlXzocRVwfieA

As Usual

Start and End

Usman Akram http://usmanlive.com CUI LAHORE 2

Page 3: React · http-app >npm install >npm start Usman Akram  CUI LAHORE 3

http-app>npm install

>npm start

Usman Akram http://usmanlive.com CUI LAHORE 3

Page 4: React · http-app >npm install >npm start Usman Akram  CUI LAHORE 3

React Vs Angular

Usman Akram http://usmanlive.com CUI LAHORE 4

Page 5: React · http-app >npm install >npm start Usman Akram  CUI LAHORE 3

>npm i axios

Usman Akram http://usmanlive.com CUI LAHORE 5

Page 6: React · http-app >npm install >npm start Usman Akram  CUI LAHORE 3

state = { persons: [] }componentDidMount() {

axios.get(`https://jsonplaceholder.typicode.com/users`)

.then(res => {

const persons = res.data;

this.setState({ persons });

})

}

Usman Akram http://usmanlive.com CUI LAHORE 6

Page 7: React · http-app >npm install >npm start Usman Akram  CUI LAHORE 3

Post Requestaxios.post(`https://jsonplaceholder.typicode.com/users`, { user })

.then(res => {

console.log(res);

console.log(res.data);

})

Usman Akram http://usmanlive.com CUI LAHORE 7

Page 8: React · http-app >npm install >npm start Usman Akram  CUI LAHORE 3

Delete Requestaxios.delete(`https://jsonplaceholder.typicode.com/users/${this.state.id}`)

.then(res => {

console.log(res);

console.log(res.data);

})

Usman Akram http://usmanlive.com CUI LAHORE 8

Page 9: React · http-app >npm install >npm start Usman Akram  CUI LAHORE 3

Base Instanceimport axios from 'axios';

export default axios.create({

baseURL: `http://jsonplaceholder.typicode.com/`

});

//api.js

Usman Akram http://usmanlive.com CUI LAHORE 9

Page 10: React · http-app >npm install >npm start Usman Akram  CUI LAHORE 3

import API from '../api';

export default class PersonList extends React.Component {

handleSubmit = event => {

event.preventDefault();

API.delete(`users/${this.state.id}`)

.then(res => {

console.log(res);

console.log(res.data);

})

}

}

Usman Akram http://usmanlive.com CUI LAHORE 10

Page 11: React · http-app >npm install >npm start Usman Akram  CUI LAHORE 3

Using Async WaithandleSubmit = async event => {

event.preventDefault();

// Promise is resolved and value is inside of the response const.

const response = await API.delete(`users/${this.state.id}`);

console.log(response);

console.log(response.data);

};

Usman Akram http://usmanlive.com CUI LAHORE 11

Page 12: React · http-app >npm install >npm start Usman Akram  CUI LAHORE 3

Request Life CycleBrowser send an options request in addition to actual request to cross domain api call

Usman Akram http://usmanlive.com CUI LAHORE 12

Page 13: React · http-app >npm install >npm start Usman Akram  CUI LAHORE 3

Request Life CycleActual Request with 201 status. Successful post

Usman Akram http://usmanlive.com CUI LAHORE 13

Page 14: React · http-app >npm install >npm start Usman Akram  CUI LAHORE 3

More Cleaner approachimport axios from "axios";

import logger from "./logService";

import { toast } from "react-toastify";

axios.interceptors.response.use(null, error => {

const expectedError =

error.response &&

error.response.status >= 400 &&

error.response.status < 500;

if (!expectedError) {

Usman Akram http://usmanlive.com CUI LAHORE 14

Page 15: React · http-app >npm install >npm start Usman Akram  CUI LAHORE 3

More Cleaner approachlogger.log(error);

toast.error("An unexpected error occurrred.");

}return Promise.reject(error);});

export default {

get: axios.get,

post: axios.post,

put: axios.put,

delete: axios.delete

};

Usman Akram http://usmanlive.com CUI LAHORE 15

Page 16: React · http-app >npm install >npm start Usman Akram  CUI LAHORE 3

React Application Wide Notifications import { ToastContainer, toast } from 'react-toastify';

import 'react-toastify/dist/ReactToastify.css';

_________________________________________________

<ToastContainer />

Usman Akram http://usmanlive.com CUI LAHORE 16

Page 17: React · http-app >npm install >npm start Usman Akram  CUI LAHORE 3

Optimistic Vs Pessimistic approach Update State Then Send Request (What if req fails?)

Vs

Send Request Then Update State

Usman Akram http://usmanlive.com CUI LAHORE 17

Page 18: React · http-app >npm install >npm start Usman Akram  CUI LAHORE 3

Optimistic Delete ApproachhandleDelete = async post => {

const originalPosts = this.state.posts;

const posts = this.state.posts.filter(p => p.id !== post.id); this.setState({ posts });

try { await http.delete(config.apiEndpoint + "/" + post.id); }

catch (ex) {

if (ex.response && ex.response.status === 404)

alert("This post has already been deleted."); this.setState({ posts: originalPosts});

}

};

Usman Akram http://usmanlive.com CUI LAHORE 18

Page 19: React · http-app >npm install >npm start Usman Akram  CUI LAHORE 3

Expected Vs Unexpected ErrorsEXPECTED: (404: not found: bad request) – CLIENT ERRORS◦ Display a specific Errors

UNEXPECTED: (network down, server down, db down, bug)◦ Log Them◦ Display a generic or friendly error

const expectedError =

error.response &&

error.response.status >= 400 &&

error.response.status < 500;

Usman Akram http://usmanlive.com CUI LAHORE 19

Page 20: React · http-app >npm install >npm start Usman Akram  CUI LAHORE 3

Log Serviceimport Raven from "raven-js";

function init() {

// Raven.config("ADD YOUR OWN API KEY", {

// release: "1-0-0",

// environment: "development-test"

// }).install();

}

Usman Akram http://usmanlive.com CUI LAHORE 20

Page 21: React · http-app >npm install >npm start Usman Akram  CUI LAHORE 3

Log Servicefunction log(error) {

// Raven.captureException(error);

}

export default {

init,

log

};

Usman Akram http://usmanlive.com CUI LAHORE 21

Page 22: React · http-app >npm install >npm start Usman Akram  CUI LAHORE 3

Vidly Backend APIhttps://github.com/mosh-hamedani/vidly-api-node

Same code is also attached in start section of

https://1drv.ms/f/s!AtGKdbMmNBGdg_MrgNlXzocRVwfieA

Or if git is installed

>git clone https://github.com/mosh-hamedani/vidly-api-node.git

>cd vidly-api-node

Access genres @ http://localhost:3900/api/genres

Disable auth in configs

Usman Akram http://usmanlive.com CUI LAHORE 22

Page 23: React · http-app >npm install >npm start Usman Akram  CUI LAHORE 3

Send a POST Request

Usman Akram http://usmanlive.com CUI LAHORE 23

Page 24: React · http-app >npm install >npm start Usman Akram  CUI LAHORE 3

Code Samplehttps://1drv.ms/f/s!AtGKdbMmNBGdg_MrgNlXzocRVwfieA

Contains an API built in express with Mongo DB

API is consumed in React

MERN Stack: DONE

Usman Akram http://usmanlive.com CUI LAHORE 24