How to put data in fields when updating? - javascript

Here is the scenario:
I want to use the same form to create a product and update a product.
The form is made with components of Material UI (TextFields).
My product creation form works (unless no image is put).
To update, I manage to return the information to my form, but I don't know how to put its data in my fields (Probably with value but I have errors (null or undefined).
Here is the head of my form (Creation and modification) :
(Same form, only the title change (Modification of a Product)
Here is the link to send the product information to be modified to my form page :
<Link to={`/produit/${produit.id}`}>
The axios request made by getProduitById(id) :
export const getProduitById = (id) => axios.get(`${APIURL}/produit/:id`.replace(':id', id));
And finally, the code of how I get the product information :
useEffect(() => {
getMarque()
if (id) {
getProduitById(id).then(response => {
if (response.data){
console.log(response.data.marqueId)
setProduit({
nom: response.data.nom,
prix: response.data.prix,
description: response.data.description,
qtestock: response.data.qtestock,
})
}
}).catch(err => console.log(err));
}
}, [])
And that's it. I try to ensure that, when I arrive on the form following my modification Link, the fields are filled with the previous information of the product
(And a little screen to show you that I get the product information in my console :)

I was able to resolve my problem with 'value' and a function 'onChange'
For anyone, here's the code :
Form :
<TextField style={TextFieldStyle} value={produit.nom} id='nom' name='nom' onChange={handleChange} placeholder='Entrez le nom du produit' type='string' fullWidth required variant='outlined' />
How I got my product information :
useEffect(() => {
if (id) {
getProduitById(id).then(response => {
if (response.data){
console.log(response.data)
setProduit({
nom: response.data.nom,
prix: response.data.prix,
description: response.data.description,
imageurl: response.data.imageurl,
qtestock: response.data.qtestock,
marqueId: response.data.marqueId,
})
console.log(produit)
}
}).catch(err => console.log(err));
}
}, [])
onChange :
const [produit, setProduit] = useState([]);
const handleChange = (e) => {
const value = e.target.value;
setProduit({
...produit,
[e.target.name]: value });
}

Related

Firestore updateDoc by id

I want update informations getting doc by id but I receive erros my code.
Idk how solve this sorry about my english. I just want to update the information I think is a basic error, but I can't solve it sorry
I receive Expected type 'Ta', but it was: a custom Aa object
const updateFields = (e) => {
e.preventDefault()
updateDoc(TopStoryAnswersCollectionRef, {
response_B6: responseB6,
response_B9: responseB9,
response_B12: responseB12,
response_B15: responseB15,
response_B18: responseB18,
response_B21: responseB21,
response_B24: responseB24,
response_B27: responseB27,
response_B28: responseB28,
response_B29: responseB29,
response_B32: responseB32,
response_B33: responseB33,
response_B34: responseB34,
response_B35: responseB35,
response_B38: responseB38,
user_uid: currentUser.uid,
}).then(() => {
alert('Updated')
})
setFormSubmitted(true)
}
Your variable TopStoryAnswersCollectionRef should be a reference to a document when using updateDoc not a reference to a collection. See sample code below:
const updateFields = (e) => {
e.preventDefault()
const TopStoryAnswersCollectionRef = doc(db, "collection-name", "document-id");
updateDoc(TopStoryAnswersCollectionRef, {
response_B6: responseB6,
response_B9: responseB9,
response_B12: responseB12,
response_B15: responseB15,
response_B18: responseB18,
response_B21: responseB21,
response_B24: responseB24,
response_B27: responseB27,
response_B28: responseB28,
response_B29: responseB29,
response_B32: responseB32,
response_B33: responseB33,
response_B34: responseB34,
response_B35: responseB35,
response_B38: responseB38,
user_uid: currentUser.uid,
}).then(() => {
alert('Updated')
})
setFormSubmitted(true)
You could also incorporate a query using where() if you still don't have the document reference to update to.
For more information, you may checkout this documentation.

jQuery or JS to pre-populate and submit a text field after dynamically generated input field finishes loading

My goal is to trigger a specific chat flow within the Microsoft Power Virtual Agent service based on the page the user is on. I haven't been able to find a way to customise the Microsoft service to dynamically start at a specific chat topic other than one fixed one using these instructions.
I want to use jQuery to pre-populate the dynamically generated text field:
$('.webchat__send-box-text-box__input').val('red');
The above code works where I see the word "red" appear in the text box very briefly but then it gets overwritten by the code that is generating the input field. If I run the above script manually from the browser console after everything has loading, it works fine.
Is there a way to customise the Microsoft webchat code to get the user to the start of a specific flow, or alternatively can I automate the insertion of the right words so that the user is automatically taken to the start of the relevant chat flow? It would be great if I could set a paramter in the webchat JS code that sets a topic right from the beginning, but I haven't found any instructions that suggests this is possible-just some basic styling parameters.
This is the code from Microsoft that generates a web chat interface:
<script src="https://cdn.botframework.com/botframework-webchat/latest/webchat.js"></script>
<script>
const styleOptions = {
// Add styleOptions to customize web chat canvas
hideUploadButton: true
};
// Add your BOT ID below
var BOT_ID = "[BOT ID VALUE REDACTED]";
var theURL = "https://powerva.microsoft.com/api/botmanagement/v1/directline/directlinetoken?botId=" + BOT_ID;
const store = window.WebChat.createStore(
{},
({ dispatch }) => next => action => {
if (action.type === "DIRECT_LINE/CONNECT_FULFILLED") {
dispatch({
meta: {
method: "keyboard",
},
payload: {
activity: {
channelData: {
postBack: true,
},
//Web Chat will show the 'Greeting' System Topic message which has a trigger-phrase 'hello'
name: 'startConversation',
type: "event"
},
},
type: "DIRECT_LINE/POST_ACTIVITY",
});
}
return next(action);
}
);
fetch(theURL)
.then(response => response.json())
.then(conversationInfo => {
window.WebChat.renderWebChat(
{
directLine: window.WebChat.createDirectLine({
token: conversationInfo.token,
}),
store: store,
styleOptions: styleOptions
},
document.getElementById('webchat');
);
})
.catch(err => console.error("An error occurred: " + err));
</script>
This is fairly easy to overcome. All you need to do is decide on how you want to identify the page being visited, filter on that in Web Chat's store, and post an activity that would trigger the appropriate topic.
In the example below, my page is title "PVA Test Page". When the page loads that has that title, using the DIRECT_LINE/CONNECT_FULFILLED action type and matching on document.title === 'PVA Test Page', then the DIRECT_LINE/POST_ACTIVITY action is dispatched. The activity I have setup is of type 'message' and sends a text value of 'store hours'. In my PVA bot I have a topic that is setup to return dialog detailing the store hours. The trigger phrases are configured to recognize that text value. So, providing all those conditions are met, the store hours are returned as a dialog when the page loads.
Si
<!DOCTYPE html>
<html>
<head>
<title>PVA Test Page</title>
[ ... ]
</head>
[ ... ]
</html>
const store = window.WebChat.createStore(
{},
( { dispatch } ) => next => action => {
if ( action.type === "DIRECT_LINE/CONNECT_FULFILLED" ) {
if (document.title === 'PVA Test Page') {
dispatch( {
meta: {
method: "keyboard",
},
payload: {
activity: {
channelData: {
postBack: true,
},
text: 'store hours',
type: "message"
},
},
type: "DIRECT_LINE/POST_ACTIVITY",
} );
}
}
return next( action );
}
);

Showing modal on successfully posting data from redux

Hey guys i am using React Hooks with redux, so what i want is lets say user need a signup on my website, so after posting his details i am sending back status :200 and if it has status:200 i am updating a state value in my userReducer like say "status" to true (which initially was false) and based on this boolean value i am showing a modal to user with the message. So code goes like
Actions.js
export const userRegisterAction = (data: any) => async (dispatch: any) => {
console.log(data);
axios.post("http://localhost:4000/register_user", data).then((res) => {
console.log("hittinh server");
console.log(res.data);
if (res.data.status == 200) {
dispatch({
type: USER_REGISTRATION_SUCCESS,
payload: res.data,
});
} else {
dispatch(errorActions());
}
});
};
Reducer.js
case USER_REGISTRATION_SUCCESS:
return {
...state,
status: true,
info: action.payload.doc.ops[0],
};
and then in my component
const user = useSelector((state: RootState) => {
console.log(state.user.info);
console.log(state.error.iserror);
return { user: state.user };
});
<IonAlert
isOpen={user.user.status == true}
cssClass="my-custom-class"
header={"User Registered!"}
backdropDismiss={false}
// subHeader={'User Registered !'}
message={"You have been registered successfully."}
// buttons={["OK"]}
buttons={[
{
text: "OK",
handler: () => {
console.log("Confirm Okay");
redirect();
},
},
]}
/>
Note. I am using redux persist and this reducer needs to be persisted for future purpose as i am gonna use this wherever i need user related task like if he needs to change password i will pick up the email from my user reducer so it doesnt gets lost on refresh
NOW COMING TO THE ISSUE, as my reducer state is persisted once the "status" is true if user wishes to signup from another account as soon as he goes to signup page he will again see the result of "ionAlert" as it will match the condition status==true , so what i am doing is on every unmount i am dispatching action which sets "status" to false, although this works fine, but i wanna know is this the correct approach , how are you all dealing with this stuff ??

React useState Hook - Can't Clear State on Form Data

Slightly novice react hooks user here. Trying to submit a blog post form, consisting of a title, author and URL. I can submit my form correctly and values are saving in database, but I can't clear the data from the form.
I'm holding state like this
const [newBlog, setNewBlog] = useState({ url: "", author: "", title: "" });
and handling form change to update state like this:
const handleBlogChange = e => {
const { name, value } = e.target;
setNewBlog({ ...newBlog, [name]: value });
};
example setup of one my input fields (identical across all three)
<form className="form" onSubmit={addBlog}>
<div className="col-lg-9">
<input
className="form-control"
id="title"
aria-describedby="emailHelp"
placeholder="Enter title"
name="title"
value={newBlog.title}
onChange={handleBlogChange}
/>
</div>
and this is my addBlog function. you can see where I commented out one version of clearing the state which is causing problems.
const addBlog = event => {
event.preventDefault();
const { url, title, author } = newBlog;
const blogObject = {
url,
title,
author
};
blogService
.create(blogObject)
.then(data => {
setBlogs(blogs.concat(data));
showMessage(`Success! ${newBlog.title} by ${newBlog.author} was added`);
// setNewBlog([...newBlog, { url: "", title: "", author: "" }]);
})
.catch(error => {
showMessage(
`Sorry can't add blog. Here's why: ${error.response.data.error}`,
false
);
});
};
I've also tried different variations which are leaving the data in the form, no errors, but not clearing out the form. Examples of this include
setNewBlog(''), setNewBlog([]) and
setNewBlog(newBlog.title='')
Nothing is working.

Axios PUT Request in React, Redux Not Working

So I want to make a PUT request to the server, but it doesn't want to work. I know that when making a PUT request you need an identifier(e.g id) for the resource and the payload to update with. So that is my problem.
In my form I have these props:
<div>
<DoorSettingsForm
onSubmit={this.submit.bind(this)}
item={this.props.location.state.item}
id={this.props.location.state.item._id}
/>
</div>
item - All the input fields, radiobuttons etc.
id - The identifier
onSubmit - the function that handles the submitting of all of the new data, here it is:
submit(values, id) {
this.props.updateSettings(values, id)
}
And inside of my really simple action I have this:
export function updateSettings(id, item) {
return dispatch => {
console.log('ID: ', id)
return axios
.put(`${settings.hostname}/locks/${id}`, item)
.then(res => console.log(res))
.catch(err => console.log(err))
}
}
One thing that I really don't understand is when I change the places of id and item on the first line the output of my console.log changes. When having id as the first parameter I get everything I've typed in my inputs (the changes) and when having item as the first parameter I'm getting this:
ID: function (action) {
if (action.payload) {
if (!(0, _isPromise2.default)(action.payload) && !(0, _isPromise2.default)(action.payload.promise)) {
return next(action);
}
Any help with my problem is really appriciated! Thanks for reading.
I forgot to call handleSubmit with my id:
form onSubmit={() => handleSubmit(id, item)}

Categories

Resources