Alex Alex - 1 month ago 8
React JSX Question

How to export several functions from a jsx file

I want to have some reusable JS code in

client.jsx
file that is imported to React components (built with webpack).
you can see
save()
,
saveWithTwoCallbacks()
,
saveWithCallback()
methods in this
client.jsx
are mostly copy-pasted. what would be the right JS syntax for
save()
methods to reuse each other?

client.jsx file:

import {browserHistory} from "react-router";

module.exports = {

saveWithTwoCallbacks: function (urlToCall, objectToSave, successCallback, errorCallback) {
$.ajax({
url: urlToCall,
contentType: 'application/json',
type: 'POST',
data: JSON.stringify(objectToSave),
success: function () {
successCallback();
},
error: function (xhr, status, err) {
errorCallback(err.toString());
}
});
},

saveWithCallback: function (urlToCall, objectToSave, callback) {
$.ajax({
url: urlToCall,
contentType: 'application/json',
type: 'POST',
data: JSON.stringify(objectToSave),
success: function () {
callback();
},
error: function (xhr, status, err) {
console.error(xhr, status, err.toString());
}
});
},

save: function (urlToCall, objectToSave, navigateTo) {
$.ajax({
url: urlToCall,
contentType: 'application/json',
type: 'POST',
data: JSON.stringify(objectToSave),
success: function () {
// console.log("saved")
browserHistory.push(navigateTo)
},
error: function (xhr, status, err) {
console.error(xhr, status, err.toString());
}
});
},

}


LoginComponent.jsx file:

import React from "react";
import {saveWithTwoCallbacks} from "./client";

class LoginComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
data : {
},
};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(e) {
setFormChangeToStateData(e, this)
}

handleSubmit(e) {
e.preventDefault();
saveWithTwoCallbacks("http://localhost:9000/login", this.state.data, onSuccess, onError);
}

render()......
}
export default LoginComponent;

Answer

what would be the right JS syntax for save() methods to reuse each other?

Nothing special. Function definitions are done via function f() { ... } and function calls via f().

In your case, you put the $.ajax call in saveWithTwoCallbacks and then just call the right function from inside the others.

To make this easier, use named exports:

export function saveWithTwoCallbacks(urlToCall, objectToSave, successCallback, errorCallback) {
  // $.ajax ...
}

export function saveWithCallback(urlToCall, objectToSave, callback) {
  saveWithTwoCallbacks(
    urlToCall,
    objectToSave,
    callback,
    (xhr, status, err) => console.error(xhr, status, err.toString())
  );
}

export function save(urlToCall, objectToSave, navigateTo) {
  saveWithCallback(urlToCall, objectToSave, () => browserHistory.push(navigateTo));
}