So, I am trying to update category data using useMutation hook in react. The fields I am going to mutate are name, description with it's associated id. But whenever I send mutation I got Missing field 'editScat' while writing result true error. Here is my code.
const [categoryName, setCategoryName] = useState("");
const [categoryDescription, setCategoryDescription] = useState("");
const [categoryId, setCategoryId] = useState("");
const EDIT_SUB_CATEGORY = gql`
mutation editScat($id: UUID!, $name: String!, $description: String!) {
editScat(id: $id, name: $name, description: $description) {
payload {
id
name
description
}
}
}
`;
const [updateCatMutation] = useMutation(EDIT_SUB_CATEGORY);
const updateMe = (e) => {
e.preventDefault();
updateCatMutation({
variables: {
id: categoryId,
name: categoryName,
description: categoryDescription,
},
optimisticResponse: true,
})
.then((res) => {
alert("Success");
})
.catch((err) => {
alert("Failed");
});
};
What did I missed 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
I'm currently fetching data from my db but for the simplicity of this Q, I have decided to manually create an example with fake data.
I'm building a search-bar for my users to look through all of the data coming from db and everything seems to be working fine when looking for a specific document, however, I want to reset the state to its original data when the input is empty.
This is what I've tried so far but with no success. Am I missing something?
const objects = [
{
_id: 0,
title: 'Title One',
},
{
_id: 1,
title: 'Title Two',
},
{
_id: 2,
title: 'Title Three',
},
]
const [keyword, setKeyword] = useState('')
const [list, setList] = useState([]);
useEffect(() => {
setList(objects);
}, [objects]);
const handleChange = () => (e) => {
e.preventDefault()
setKeyword(e.target.value)
if (keyword !== '') {
const result = objects.filter((object) => {
return object.title.toLowerCase().startsWith(keyword.toLowerCase())
})
setList(result)
} else {
// THIS IS WHERE THE PROBLEM RESIDES...
console.log('Original data')
setList(objects)
}
}
This is the current output:
What you're doing wrong is in these lines
setKeyword(e.target.value)
if (keyword !== '') {
The state is updated asynchronously, and the value of the keyword will be old.
What you can do is update the state in handleChange and then have a separate useEffect to update the results:
const [keyword, setKeyword] = useState('')
const [list, setList] = useState([]);
useEffect(() => {
setList(objects);
}, [objects]);
useEffect(() => {
if (keyword !== '') {
const result = objects.filter((object) => {
return object.title.toLowerCase().startsWith(keyword.toLowerCase())
})
setList(result)
} else {
// THIS IS WHERE THE PROBLEM RESIDES...
console.log('Original data')
setList(objects)
}
}, [keyword]);
const handleChange = () => (e) => {
e.preventDefault()
setKeyword(e.target.value)
}
State setters are asynchronous. The code following a state update (your if(keyword) may be run before the state update is complete (setKeyword)
Your code may be simplified if you merge keyword & list in a single object.
var [searchState, setSearchState] = useState({keyword: '', list: objects.slice());
handleChange=(evt)=>{
let word = evt.target.value;
let wordLower= word.toLowerCase();
setSearchState({
keyword:word,
list: word?objects.filter(o=>o.title.toLowerCase().startsWith(wordLowerCase):objects.slice()
});
};
Or you can use class based component where the state is a single object.
My Code looks like this:
interface MutationProps{
username: any,
Mutation: any
}
const UseCustomMutation: React.FC<MutationProps> = (MutationProps: MutationProps) => {
const [myFunc, {data, error}] = useMutation(MutationProps.Mutation);
useEffect(() => {
myFunc({variables:{username: MutationProps.username}})
console.log(JSON.stringify(data))
console.log(JSON.stringify(error, null , 2))
}, [])
return data
}
export const DisplayUser = () => {
const GET_USER = gql`
mutation GetUser($username: String!){
getUser(username: $username) {
pfp
username
password
age
CurrentLive
ismod
description
fullname
}
}
`
const {username} : {username: any} = useParams()
const MyData = UseCustomMutation(username, GET_USER)
console.log(JSON.stringify(MyData))
But I get this error back: ×
Argument of undefined passed to parser was not a valid GraphQL DocumentNode. You may need to use >'graphql-tag' or another method to convert your operation into a document
How about your code looks like this:
interface MutationProps {
username: string;
Mutation: any;
}
const UseCustomMutation: React.FC<MutationProps> = ({ username, Mutation }) => {
const [functionForDoingAction, { data, loading, error }] = useMutation(
Mutation,
{
variables: {
username,
},
}
);
useEffect(() => {
// fn trigger for change data
functionForDoingAction({
variables: {
username: "string_value",
},
});
console.log(JSON.stringify(data));
console.log(JSON.stringify(error, null, 2));
}, []);
if (loading) return "loading...";
if (error) return `Submission error! ${error.message}`;
return data;
};
export const DisplayUser = () => {
const GET_USER = gql`
mutation GetUser($username: String!) {
getUser(username: $username) {
pfp
username
password
age
CurrentLive
ismod
description
fullname
}
}
`;
const { username }: { username: string } = useParams();
const MyData = UseCustomMutation(username, GET_USER);
console.log(JSON.stringify(MyData));
};
you can pass an argument directly to the useMutation hook which they provide as an Options parameter. Or is the direct trigger function from the hook you get.
When i try adding comment to the post i get this error:
FirebaseError: Function CollectionReference.doc() cannot be called with an empty path.
Here is my code:
Im using this to push to Firebase, postId is from Redux.
const postId = useSelector(selectPostId);
useEffect(() => {
// za komentiranje na slika
if (postId) {
db.collection("posts")
.doc(postId)
.collection("comments")
.orderBy("timestamp", "desc")
.onSnapshot((snapshot) => {
setComments(snapshot.docs.map((doc) => doc.data()));
});
}
}, [postId]);
const postComment = (e) => {
e.preventDefault();
db.collection("posts").doc(postId).collection("comments").add({
text: comment,
username: user.displayName,
timestamp: firebase.firestore.FieldValue.serverTimestamp(),
});
setComment("");
};
Here is the Redux :
export const postSlice = createSlice({
name: "post",
initialState: {
postId: null,
commentId: null,
},
reducers: {
setPost: (state, action) => {
state.postId = action.payload.postId;
},
setComments: (state, action) => {
state.commentId = action.payload.commentId;
},
},
});
export const { setPost, setComments } = postSlice.actions;
export const selectPostId = (state) => state.post.postId;
export const selectCommentId = (state) => state.post.commentId;
export default postSlice.reducer;
Looks like you are passing a wrong document id to posts collection:
verify that postId global state has a value.
if postId is a valid value then, check posts collection and see if you are passing the right id to the right collection " Database Architecture "
that is what the error is about.
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.