i need to insert a prescription details in mySQL database, but i struggle to inserting it with array data.
I have 2 states, 1 array state to keep the medicines i push into it then send the values to axios when done & 1 state to save the selected medicine.
My options example: using react-select
const medicine = [
{ id_obat: '123', label: 'Amoxcilin 300mg' },
{ id_obat: '321', label: 'Ibuprofen 500ml' }
];
React codes:
const [values, setValues] = useState([]);
const [meds, setMeds] = useState({
obat: {},
cara_pakai: '',
kuantitas: ''
});
const initialState = {
obat: {},
cara_pakai: '',
kuantitas: ''
};
const handleChange = obat => {
setMeds({ ...meds, ['obat']: obat });
};
const addMed = () => {
setValues([...values, meds]);
setMeds({ ...initialState });
};
const onSubmit = e => {
e.preventDefault();
addPrescript(values);
};
My axios action to send it to my API:
export const addPrescript = values => async dispatch => {
const config = {
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
};
const form = qs.stringify(values);
try {
const res = await axios.post('/api/prescription', form, config);
dispatch({ type: ADD_PRESCRIPT, payload: res.data });
dispatch(setAlert('Submit Success', 'success', 3000));
} catch (err) {
let errors = err.response.data.errors;
if (errors) {
errors.forEach(error => dispatch(setAlert(error.msg, 'danger')));
}
}
};
My prescription controller:
exports.createPrescription = async (req, res) => {
const { id_obat, cara_pakai, kuantitas, deskripsi } = req.body;
const p_value = {
deskripsi: deskripsi
};
const p_sql = 'INSERT INTO resep SET ?';
const d_sql = 'INSERT INTO detail_resep SET ?';
conn.query(p_sql, p_value, (error, p_result) => {
if (error) throw error;
let d_value = [
{
id_resep: p_result.insertId,
id_obat: id_obat,
cara_pakai: cara_pakai,
kuantitas: kuantitas
}
];
conn.query(d_sql, [d_value], (error, d_result) => {
if (error) throw error;
res.status(200).json({
values: d_result
});
});
});
};
My backend server keep sending me error [You have an error in your SQL syntax], i dont know how to solve it.
my API required req.body to submit is | id_resep | id_obat | cara_pakai | kuantitas | to be success inserted. i dont know if im wrong with the stringify. my first time work with array data :>
Any help appreciated.
look like below statement has to change
const p_sql = 'INSERT INTO resep SET ?';
const d_sql = 'INSERT INTO detail_resep SET ?';
to
const p_sql = 'INSERT INTO resep( {columnname}) values({value1,value2})';
const d_sql = 'INSERT INTO detail_resep ( {columnname}) values({value1,value2}))';
change {columnname } to your column name and corresponding values in {value}
Basically insert statement syntax is not correct here.
Related
I have 4 functions, for 1st three functions, I can send the data in provide. For 4th function(
getViewApplicationDetails
), I am trying to fetch api and get application name, now I want that in mounted because, I want the application name as soon as component is rendered so I am trying to execute it in mounted but when I call the it, it's giving me error. Initially application name is empty and it should have the current application name when I fetch the api, the same application name will be used in provide and then I can use that in inject and then in any other component.
import { computed, inject, onMounted, provide, reactive } from "vue";
export const initStore = () => {
onMounted(()=>{
this.getViewApplicationDetails()
});
// State
const state = reactive({
name: "Bob Day",
email: "bob#martianmovers.com",
applicationName: "",
breadcrumbsData: [
{
name: "Home",
text: 'Home',
disabled: false,
href: '/'
}
]
});
// Getters
const getUsername = computed(() => state.name);
const getEmail = computed(() => console.log("state.email",state.email));
const getBreadcrumbsData=computed(()=>state.breadcrumbsData)
console.log("state.applicationName",state.applicationName)
//this is the temporary function
const getApplicationName=computed(()=>state.applicationName)
const getViewApplicationDetails=computed(()=> {
var viewApplicationDetailsParams = {
applicationId: this.$route.query.applicationId,
applicationStatus:this.$route.query.appStatus,
authType: "api",
clientId: process.env.VUE_APP_EXTERNAL_API_CLIENT_ID,
clientSecret: process.env.VUE_APP_EXTERNAL_API_CLIENT_SECRET
};
axios({
method: "post",
url: process.env.VUE_APP_BLUJ_BACKEND_URL + "/viewapplicationDefinition",
data: viewApplicationDetailsParams,
headers: {
"content-type": "application/json",
},
})
.then((response) =>{
this.viewDefinitionResponse = response.data.Definitions;
let applicationName = viewDefinitionResponse.application_display_name.en;
console.log("tyfgyhkjlfhgjklnm",applicationName)
setApplicationName(applicationName)
})
.catch((error) => {
console.log("error", error);
});
});
getViewApplicationDetails()
// Mutations
const setUsername = (name) => {
state.name = name;
};
const setEmail = (email) => {
state.email = email;
};
const setBreadCrumbsData=(breadcrumbsData)=>{
state.breadcrumbsData=breadcrumbsData;
}
const setApplicationName=(appName)=>{
state.applicationName=appName
}
// Actions
const updateUsername = (name) => {
setUsername(name);
};
const updateEmail = (email) => {
setEmail(email);
};
provide("getUsername", getUsername);
provide("getEmail", getEmail);
provide("updateUsername", updateUsername);
provide("updateEmail", updateEmail);
provide("getViewApplicationDetails", getViewApplicationDetails);
provide("getApplicationName", getApplicationName);
provide("getBreadcrumbsData", getBreadcrumbsData);
};
export const useStore = () => ({
getUsername: inject("getUsername"),
getEmail: inject("getEmail"),
updateUsername: inject("updateUsername"),
updateEmail: inject("updateEmail"),
viewApplicationDetails: inject("getViewApplicationDetails"),
getBreadcrumbsData: inject("getBreadcrumbsData"),
getApplicationName: inject("getApplicationName")
});
This is the code snippet.
const getUsername = computed(() => state.name);
const getEmail = computed(() => console.log("state.email",state.email));
const getBreadcrumbsData=computed(()=>state.breadcrumbsData)
I am getting data for this, but for getViewApplicationDetails, it's not working. While hovering over rest of the functions, it is showing "const getUsername: ComputedRef", like this. But, for getViewApplicationDetails, it shows "const getViewApplicationDetails: ComputedRef", this. I think it is not taking it as function or something. Error image is in the link.enter image description here
Like
[
{
"enear": "",
"inten": 1,
"sctor": "Eny",
"topic": "",
"insight": ""
},
{
"enear": "",
"inten": 1,
"sctor": "Eny",
"topic": "",
"insight": ""
}
]
If possible how to write the nodejs code
This is my code
router.post("/post" , async (req,res) => {
const data = new Model(req.map(r => ({
enear: r.body.enear,
inten:r.body.inten,
sctor: r.body.sctor,
topic: r.body.topic,
insight: r.body.insight,
})))
try{
const dataToSave = await data.save()
res.status(200).json(dataToSave)
}catch(error){
res.status(400).json({message:error.message})
}
})
Does map works here?
I have tried using map . Is there any possible way please suggest
You can send an array in the body part and access an array using
req.body and use req.body.map here if it satisifies the condition
Array.isArray(req.body)
router.post("/post" , async (req,res) => {
const { body } = req;
if (Array.isArray(body)) {
const data = new Model(body.map(r => ({
enear: r.body.enear,
inten:r.body.inten,
sctor: r.body.sctor,
topic: r.body.topic,
insight: r.body.insight,
})))
try{
const dataToSave = await data.save()
res.status(200).json(dataToSave)
}catch(error){
res.status(400).json({message:error.message})
}
}
You can specify the array in Body -> Raw (select JSON format):
Then, you should be able to access your data with:
router.post('/post', async (req, res) => {
const { array } = req.body;
try {
const savedData = [];
for (const obj of array) {
const data = await Model.create({
enear: obj.enear,
inten: obj.inten,
sctor: obj.sctor,
topic: obj.topic,
insight: obj.insight,
});
savedData.push(data);
}
res.status(200).json(savedData);
} catch (error) {
res.status(400).json({ message: error.message });
}
});
I'm new here on the site, and new to React.
I built a function that works great in nodejs. There are rare cases where I want to run this function according to the parameters I send it to, so I try to send it the parameters but I think I can not, I try to print it - and I do not get a print of the parameters I want to send.
i run the function throw click at buttom in react:
<Button onClick={() => {
const result = [1,2,3,4,5,"test"];
props.makeMatchVer2(result);
}}>
make match ver2
</Button>
the action I'm run in axios:
export const makeMatchVer2 = (data) => (dispatch) => {
dispatch({ type: LOADING_DATA });
axios
.get('/kmeans', {
params: {
filterArray: data
}
})
.then((res) => {
dispatch({
type: MAKE_MATCH,
payload: res.data
});
})
.catch((err) => {
dispatch({
type: MAKE_MATCH,
payload: []
});
});
};
the function I'm build in nodeJS:
exports.addUserKmeansMatch = (req, res) => {
console.log("addUserKmeansMatch function start:");
console.log(req.data);
if(req.params)
{
console.log(req.params);
}
let userIndex = 0;
let engineers = [];
let engineersHandles = [];
let engineerDetailsNumeric = {};
db.collection("preferences").get().then(querySnapshot => {
querySnapshot.forEach(doc => {
const engineerDetails = doc.data();
if (engineerDetails.handle === req.user.handle) {
engineersHandles.unshift(engineerDetails.handle);
delete engineerDetails.handle;
engineerDetailsNumeric = convertObjectWithStrToNumber(engineerDetails);
engineers.unshift(engineerDetailsNumeric);
}
else {
engineersHandles.push(engineerDetails.handle);
delete engineerDetails.handle;
engineerDetailsNumeric = convertObjectWithStrToNumber(engineerDetails);
engineers.push(engineerDetailsNumeric);
}
});
kmeans.clusterize(engineers, { k: 4, maxIterations: 5, debug: true }, (err, result) => {
if (err) {
console.error(err);
return res.status(500).json({ error: err.code });
} else {
const cluster = result.clusters;
let foundedMatches = GetUserSerialGroup(userIndex, [...cluster], [...engineers]);
let foundedMatchesHandle = GetUserSerialGroupHandle(userIndex, [...cluster], [...engineersHandles]);
let totalTest = {
foundedMatches: foundedMatches,
foundedMatchesHandle: foundedMatchesHandle,
cluster: cluster,
engineersHandles: engineersHandles,
engineers: engineers
};
let userMatchHandle = reduceUserMatchHandle(foundedMatchesHandle);
userMatchHandle.handle = req.user.handle;
db.doc(`/match/${req.user.handle}`)
.set(userMatchHandle)
.then(() => {
return res.json({ message: "Details added successfully" });
})
.catch((err) => {
console.error(err);
return res.status(500).json({ error: err.code });
});
}
})
})
};
Through the button, I send parameters to the function, but I do not see their print, probably something does not work, but I do not know why, I'm new to it
makeMatchVer2 is a thunk. You should call it with dispatch: dispatch(props.makeMatchVer2(result))
The code is correct, I accidentally sent the wrong object, I have 2 objects with almost identical names, one array and the other an object. And I accidentally sent the object instead of the array, it's working right now, thank you.
I'm saving data in the collection in the following way:
const userEntry= {
UserId: "I want documentID here",
UserName: "",
creationDate: ""
}
const churchResult = await saveChurchData(userEntry)
const saveData = async (data: object) => {
return database.collection('users').add(data)
.then(snapshot => {
return snapshot.get().then(doc => {
doc.data()
return doc.id
}).catch(err => {
console.log('Error getting documents', err);
return null;
});
}).catch(err => {
console.log('Error getting documents', err);
return null;
});
}
Is there any way that I store "documentID" of users table in the place of UserId. How can we do that in firebase cloud functions? I'm unable to find a way to store the documentID in the documentation.
I tried following, but it is giving wrong ID not docuemntID:
const key =firebase.database().ref().push()
Since I don't see any saveChurchData() method in your code, I make the assumption that instead of doing
const churchResult = await saveChurchData(userEntry)
you wan to do
const churchResult = await saveData(userEntry)
The following would do the trick, by using the doc() method without specifying any documentPath:
const userEntry = {
UserName: "",
creationDate: ""
}
const churchResult = await saveData(userEntry)
const saveData = async (data: object) => {
try {
const docRef = database.collection('users').doc();
const docId = docRef.id;
await docRef.set({ UserId: docId, ...data });
return docId;
} catch (error) {
//...
}
}
When a user makes a post, I want to take the pushKey of the post and then add it in to the User object in order to store in a list of posts they have made.
I had assumed that my logic was correct but it seems not. Everything is console logging so far.
Here is the Create Post action:
export const createPostNoImage = (text, firstName, university, avatar) => {
const timeDate = new Date().getTime();
const { currentUser } = firebase.auth();
const { uid } = currentUser;
const anonAvatarKey = Math.floor(Math.random() * 10);
return (dispatch) => {
const pushKey = firebase.database().ref('/social/posts/').push().key;
const postObject = {
text,
comment_count: 0,
vote_count: 0,
author: {
uid,
anon_avatar_key: anonAvatarKey,
first_name: firstName,
photo_avatar: avatar,
university
},
created_at: timeDate,
};
firebase.database().ref(`/social/posts/${pushKey}`)
.update(postObject)
.then(() => {
postObject.uid = pushKey;
addPostIdToProfile(pushKey);
dispatch({ type: CREATE_POST, payload: postObject });
});
};
};
The above works just fine, I then call the addPostIdToProfile() function:
const addPostIdToProfile = (pushKey) => {
const { currentUser } = firebase.auth();
console.log(pushKey);
firebase.database().ref(`/social/users/${currentUser.uid}`)
.update((user) => {
if (!user.posts) {
user.posts = {};
}
user.posts[pushKey] = true;
return user;
});
};
It is this that is not updating in the database. Can someone please tell me why?