Skip to content

Commit

Permalink
convert xhr requests to axios
Browse files Browse the repository at this point in the history
  • Loading branch information
EhsanParsania committed Jun 8, 2021
1 parent 1fcb7cf commit 1d1ee1c
Show file tree
Hide file tree
Showing 8 changed files with 62 additions and 127 deletions.
3 changes: 1 addition & 2 deletions src/App.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,14 @@ import { Component } from "react"
import "./App.css"
import { Datagrid, MenuItems } from "./components/index"
import { getData } from "./model/AjaxRequests"
import { InputData } from './components/index'
import {Paginator} from './components/index'

class App extends Component {

componentDidMount() {
getData('orders')
.then(data => {
const fetchedData = JSON.parse(data)
const fetchedData = data
const dataLength = fetchedData.length
this.setState({ data: fetchedData, title: 'orders', dataLength:dataLength })
})
Expand Down
2 changes: 1 addition & 1 deletion src/components/Avatar/Avatar.component.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ class Avatar extends Component {
const { src } = this.props
return (
<div style={{width:"40px", height:"40px"}}>
<img style={{width:"40px", height:"40px",borderRadius:"50%"}} src={src} />
<img style={{width:"40px", height:"40px",borderRadius:"50%"}} src={src} alt='pic' />
</div>
)
}
Expand Down
5 changes: 0 additions & 5 deletions src/components/DataGrid/DataGrid.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,18 +23,13 @@ class Datagrid extends Component {
padding: '0 20px'
}

constructor(props) {
super(props)
}

modalDisplayHandler = () => {
this.setState({ showModel: !this.state.showModel })
}

render() {
const { data, title } = this.props
const fields = Object.keys(data[0]).filter(field => field !== "id")
console.log(fields)
return (
<div id="datagrid">
<Modal activeStyle={this.state.showModel ? this.activeModalStyle : {}} generalStyle={this.generalModalStyle}>
Expand Down
78 changes: 17 additions & 61 deletions src/components/InputFile/InputFile.component.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import axios from 'axios'
import { Component } from 'react'
import style from './InputFile.module.css'
import { uploadCustomerData } from '../../model/AjaxRequests'


class InputFile extends Component {
Expand All @@ -9,39 +10,16 @@ class InputFile extends Component {
}


//xhr request to post image with form data ( multipart/form-data )

uploadFile() {
return new Promise(function (resolve, reject) {
const image = document.getElementById('input').files[0]
const name = document.getElementById('input-name').value
const age = document.getElementById('input-age').value
const gender = document.getElementById('input-gender').value

var data = new FormData();
data.append("image", image);
data.append("name",name)
data.append("age",age)
data.append("gender",gender)

var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.addEventListener("readystatechange", function () {
if (this.readyState === 4) {
if (this.status >= 200 && this.status < 400) {
console.log(this.responseText);
if (image) {
resolve({isUpload:true,fileName:this.response})
}
}
else {
reject('file not sent')
}
}
});
xhr.open("POST", "http://localhost:3001/customers");
xhr.send(data);
})
// return new Promise(function (resolve, reject) {
const image = document.getElementById('input').files[0]
const name = document.getElementById('input-name').value
const age = document.getElementById('input-age').value
const gender = document.getElementById('input-gender').value

// it returns true or false for closing Modal (axios request)
return uploadCustomerData(image, name, age, gender)
}


Expand All @@ -63,36 +41,14 @@ class InputFile extends Component {
}


uploadData = async () => {
const name = document.getElementById('input-name').value
const age = document.getElementById('input-age').value
const gender = document.getElementById('input-gender').value

const url = 'http://localhost:3001/customers'
const data = {
name,
age,
gender
}
axios.post(url, data)

}



submitForm = async (e) => {
e.preventDefault();

try {
// post file and get boolean result
const isUpload = await this.uploadFile()

// const {isUpload,fileName} = await this.uploadFile()
// console.log(isUpload,fileName)

//post input data to json-server


// remove modal
this.props.closeModal(isUpload)
}
Expand All @@ -106,20 +62,20 @@ class InputFile extends Component {

render() {
return (
<form action='http://localhost:3001/upload' method='POST' encType='multipart/form-data' onSubmit={this.submitForm} className={style.input_file_container}>
<form onSubmit={this.submitForm} className={style.input_file_container}>
<label className={style.input_file_label}>
<span className={style.file_name} >{this.state.fileName}</span>
<input id='input' type="file" name='image' onChange={this.handleChange} className={style.input_file} accept='image/*' />
<input id='input' type="file" onChange={this.handleChange} className={style.input_file} accept='image/*' />
<i className={style.upload_button}>Upload File</i>
</label>
<img src="" className={style.image_container} id="output" alt="pic..."></img>

<label className={style.input_labels} for='input-name'>Name</label>
<input id='input-name' className={style.inputs} name='name' type='text' />
<label className={style.input_labels} for='input-age'>Age</label>
<input id='input-age' className={style.inputs} age='age' type='text' />
<label className={style.input_labels} for='input-gender'>Gender</label>
<input id='input-gender' className={style.inputs} gender='gender' type='text' />
<label className={style.input_labels} for='input-name'>Name</label>
<input id='input-name' className={style.inputs} type='text' />
<label className={style.input_labels} for='input-age'>Age</label>
<input id='input-age' className={style.inputs} type='text' />
<label className={style.input_labels} for='input-gender'>Gender</label>
<input id='input-gender' className={style.inputs} type='text' />
<button type='submit' className={style.submit_button}>Submit</button>
</form>
)
Expand Down
14 changes: 6 additions & 8 deletions src/components/MenuItems/MenuItems.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,18 +8,16 @@ class MenuItems extends Component {

handleClick = async (dataName) => {
const data = await getData(dataName)
const fetchedData = JSON.parse(data)
this.props.setItemsStart(0, 1)
this.props.dataSetter(fetchedData, dataName)
this.props.dataSetter(data, dataName)
}

// put handleClick in should update to back and forward work on hash change
shouldComponentUpdate() {
onhashchange = async () => {
const hash = window.location.hash.slice(1)
console.log(hash)
await this.handleClick(hash)
}

return true
}

Expand All @@ -28,22 +26,22 @@ class MenuItems extends Component {
<div className={style.sideNav} id="menuitems">
<div className={style.sideDiv}>
<span className={style.sideSpan}>
<img className={style.sideImg} src="https://aux.iconspalace.com/uploads/dashboard-icon-256-1241939503.png" /></span>
<img className={style.sideImg} src="https://aux.iconspalace.com/uploads/dashboard-icon-256-1241939503.png" alt=''/></span>
<a className={style.sideLink} href="#customers" >Dashboard</a>
</div>
<div className={style.sideDiv}>
<span className={style.sideSpan}>
<img className={style.sideImg} src="https://img.icons8.com/pastel-glyph/2x/purchase-order.png" /></span>
<img className={style.sideImg} src="https://img.icons8.com/pastel-glyph/2x/purchase-order.png" alt=''/></span>
<a className={style.sideLink} href="#orders" >Orders</a>
</div>
<div className={style.sideDiv}>
<span className={style.sideSpan}>
<img className={style.sideImg} src="https://cdn.iconscout.com/icon/free/png-256/customers-11-866159.png" /></span>
<img className={style.sideImg} src="https://cdn.iconscout.com/icon/free/png-256/customers-11-866159.png" alt=''/></span>
<a className={style.sideLink} href="#products" >Products</a>
</div>
<div className={style.sideDiv}>
<span className={style.sideSpan}>
<img className={style.sideImg} src="https://cdn2.iconfinder.com/data/icons/e-commerce-line-4-1/1024/open_box4-512.png" /></span>
<img className={style.sideImg} src="https://cdn2.iconfinder.com/data/icons/e-commerce-line-4-1/1024/open_box4-512.png" alt=''/></span>
<a className={style.sideLink} href="#customers" >Customers</a>
</div>
</div>
Expand Down
3 changes: 0 additions & 3 deletions src/components/Modal/Modal.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,6 @@ import { Component } from "react"
import styles from "./Modal.module.css"

class Modal extends Component {
constructor(props) {
super(props)
}

render() {
const { activeStyle, generalStyle, children } = this.props
Expand Down
1 change: 0 additions & 1 deletion src/index.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import React from 'react';
import ReactDOM from 'react-dom';
import {getData} from './model/AjaxRequests'
import {App} from "./App"
import {Main} from './layouts/Main.layout'

Expand Down
83 changes: 37 additions & 46 deletions src/model/AjaxRequests.js
Original file line number Diff line number Diff line change
@@ -1,55 +1,46 @@
import axios from 'axios'

const url = 'http://localhost:3001'

// get data request function
async function getData(dataName) {
const currentUrl = url + "/" + dataName
return new Promise(function (resolve, reject) {
let xhr = new XMLHttpRequest()
xhr.open('GET', currentUrl)
xhr.send()
xhr.onreadystatechange = function () {
if (this.readyState === 4) {
if (this.status >= 200 && this.status < 400) {
console.log('request resolved')
resolve(xhr.responseText)
}
else {
console.log(xhr.status)
reject(xhr.status)
}
}
}
})
}

//it gets an object and a name for generating post url :
async function postData(dataObject, dataName) {
return new Promise(function (resolve, reject) {
var data = JSON.stringify(dataObject);

const xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (this.readyState === 4) {
if (this.status >= 200 && this.status < 400) {
resolve(console.log('data sent'))
}
else {
reject(console.log('rejected :' + xhr.status))
}
console.log(this.responseText);
}
};
const url = "http://localhost:3001/" + dataName
console.log(url)
xhr.open("POST", url);
xhr.setRequestHeader("Content-Type", "application/json");

xhr.send(data);
})
function getData(dataName) {
const currentUrl = url + '/' + dataName
return axios.get(currentUrl)
.then((res) => res.data)
.catch(error => console.log(error))
}



function uploadCustomerData(image, name, age, gender) {
const currentUrl = url + '/' + 'customers'
console.log(currentUrl)
//init a body form data
let bodyFormData = new FormData()

bodyFormData.append('image', image)
bodyFormData.append('name', name)
bodyFormData.append('age', age)
bodyFormData.append('gender', gender)


return axios({
url: currentUrl,
method: 'POST',
data: bodyFormData,
Headers: { "Content-Type": "multipart/form-data" }
})
.then(res => {

//return true for closing modal
return true
})
.catch(error => {
console.log(error)
//return false to not closing Modal
return false
})
}


export { getData, postData }
export { getData, uploadCustomerData }

0 comments on commit 1d1ee1c

Please sign in to comment.