How to save formData from react class component? - javascript

I include my code. Can you tell me how do I save? After clicking the save button FormData is null. How do upload images using the Cloudinary library and React class component? API is working properly. Body data pass to the API as form-data. This is my API response =>
{
"code": 200,
"success": true,
"status": "OK",
"ItemDetails": {
"_id": "6125cc9ecfde9b2eb45d1909",
"item_name": "Chicken Rices",
"item_type": "Rice",
"item_time": "Lunch",
"item_price_type_small": 120,
"item_price_type_medium": 170,
"item_price_type_large": 200,
"item_url": "https://res.cloudinary.com/doelyvv2h/image/upload/v1629867165/MenuList/ldmny2cxvhqh7fisy1ex.jpg",
"cloudinary_id": "MenuList/ldmny2cxvhqh7fisy1ex",
"createdAt": "2021-08-25T04:52:46.726Z",
"updatedAt": "2021-08-25T04:52:46.726Z",
"__v": 0
},
"message": "Item added successfully."
}
import React, { Component } from "react";
import { Link } from "react-router-dom";
import User from "../../../assets/images/user.png";
import { toast } from "react-toastify";
import { APIURL } from "../../API/environment";
const initialState = {
item_name: "",
item_type: "",
item_time: "",
item_price_type_small: "",
item_price_type_medium: "",
item_price_type_large: "",
image: "",
};
class AddFoodMenu extends Component {
constructor(props) {
super(props);
this.state = initialState;
this.onChange = this.onChange.bind(this);
this.onSubmit = this.onSubmit.bind(this);
}
onChange(e) {
this.setState({ [e.target.name]: e.target.value });
}
onSubmit(event) {
event.preventDefault();
let item_name = this.state.item_name;
let item_type = this.state.item_type;
let item_time = this.state.item_time;
let item_price_type_small = this.state.item_price_type_small;
let item_price_type_medium = this.state.item_price_type_medium;
let item_price_type_large = this.state.item_price_type_large;
let image = this.state.image;
console.log("object", item_name);
let formData = new FormData();
formData.append("item_name", item_name);
formData.append("item_type", item_type);
formData.append("item_time", item_time);
formData.append("item_price_type_small", item_price_type_small);
formData.append("item_price_type_medium", item_price_type_medium);
formData.append("item_price_type_large", item_price_type_large);
formData.append("image", image);
console.log(formData);
axios.post(`${APIURL}/menulist/add-item-to-menu`,
{ method : "POST",
body : formData}
).then((res) => {
console.log("res", res);
if (res.data.code === 200) {
toast.success(res.data.message);
window.setTimeout(function () {
window.location.href = "/login";
}, 2000);
} else {
toast.error(res.data.message);
}
});
}

I couldn't understand you're question. Post full code or some more clarity.
My suggestion would be to set the value to a state with API response.

Related

How can i clear the chat input-box after sending the message(from suggestion) in botframework webchat?

i'm working on a bot application using react js and botframework webchat. The thing is that i want to clear the text input box (from where msgs are sent) after sending the message - which is selected from the suggestion. The Suggestion list(or autocomplete component) is a custom coded one. And What i mean is that if i type "hr" the suggestion list popup will come and if i click on one option from the suggestion, say 'hr portal', it will be sent, but what i wrote ie "hr" remains there in the input field and i want to clear that. And please note that If i type something and send its working fine. The problem is only when i type something and select something from the suggestion. Everything else is fine. How can i clear that. Any help would be really appreciated.
please find the below image for more understanding.
here's my code;
import React from 'react';
import { DirectLine, ConnectionStatus } from 'botframework-directlinejs';
import ReactWebChat from 'botframework-webchat';
import './ChatComponent.css';
var val;
var apiParameters = [];
var currentFocus = -1;
export default class extends React.Component {
constructor(props) {
super(props);
this.state = {
token: '',
conversationId: '',
directLine: {},
view: false,
feedBack: null,
value: '',
popupContent: '',
storeValue: '',
suggestions: [],
suggestionCallback: '',
suggestionTypedText: "",
typingChecking: "false",
};
this.handleTokenGeneration = this.handleTokenGeneration.bind(this);
this.handleChange = this.handleChange.bind(this);
this.handleSaveFeedback = this.handleSaveFeedback.bind(this);
this.handleSuggestion = this.handleSuggestion.bind(this);
this.handleClose = this.handleClose.bind(this);
this.handleSuggestionClick = this.handleSuggestionClick.bind(this);
this.handleKeyDown = this.handleKeyDown.bind(this);
this.moveHighlight = this.moveHighlight.bind(this);
this.getSuggestionHtml = this.getSuggestionHtml.bind(this);
}
getSuggestionHtml(suggestion) {
const lowerCaseSuggestion = suggestion.toLowerCase();
return {
__html: lowerCaseSuggestion.includes(this.state.suggestionTypedText) ? lowerCaseSuggestion
.replace(this.state.suggestionTypedText, `<b>${this.state.suggestionTypedText}</b>`) : lowerCaseSuggestion
};
}
handleTokenGeneration = async () => {
console.log("11111");
const response = await fetch(`api/TokenGenerationService/GetToken`);
const data = await response.json();
this.setState({
token: data.categoryObject.token, conversationId:
data.categoryObject.conversationId
});
this.state.directLine = new DirectLine({ token: this.state.token });
this.setState({ view: true });
this.setState({ typingChecking: "true" });
console.log("conversationId");
};
async handleSuggestion(val, store) {
if (val === "") {
this.setState({
suggestions: []
});
}
else {
apiParameters = [];
var valuess = null;
const response = await fetch(`api/TokenGenerationService/GetAzureSearch?myparam1=${val}`);
const data = await response.json();
var values = ["Hello", "yes", "no", "exit", "Welcome", "Thank You", "Approve", "Apply leave", "Reject", "Absence Balance", "Leave Balance", "Upcoming Holidays", "Apply Comp-Off", "Approve Leave", "Raise Incident Tickets", "Project Allocation Info", "Reporting Manager Change", "Reporting Manager Approval", "Approve Isolve Tickets", "My Manager", "My Account Manager", "Generate Salary Certificate", "Isolve Ticket Status", "Internal Job Posting", "My Designation", "My Joining Date", "RM Approval", "RM Change", "Resource Allocation", "ESettlement Approval", "SO Approval", "Cash advance Approval", "Purchase Request Approval", "Referral status", "HR Ticket", "Platinum Support"];
valuess = values.filter(s =>
s.toLocaleLowerCase().startsWith(val.toLowerCase())
);
valuess = valuess.concat(data.az_search);
this.setState({
suggestions: valuess,
suggestionCallback: store,
suggestionTypedText: val.toLowerCase()
});
// alert(data.az_search);
var totCount = data.az_search;
console.log("kkkkkk" + totCount);
}
}
moveHighlight(event, direction) {
event.preventDefault();
const { highlightedIndex, suggestions } = this.state;
if (!suggestions.length) return;
let newIndex = (highlightedIndex + direction + suggestions.length) % suggestions.length;
if (newIndex !== highlightedIndex) {
this.setState({
highlightedIndex: newIndex,
});
}
}
keyDownHandlers = {
ArrowDown(event) {
this.moveHighlight(event, 1);
},
ArrowUp(event) {
this.moveHighlight(event, -1);
},
Enter(event) {
const { suggestions } = this.state;
if (!suggestions.length) {
// menu is closed so there is no selection to accept -> do nothing
return
}
event.preventDefault()
this.applySuggestion(suggestions[this.state.highlightedIndex]);
},
}
handleKeyDown(event) {
// console.log("lokkkkkkkkkkkk")
if (this.keyDownHandlers[event.key])
this.keyDownHandlers[event.key].call(this, event)
}
async handleSuggestionClick(event) {
await this.applySuggestion(event.currentTarget.textContent);
}
async applySuggestion(newValue) {
//newValue = null;
await this.setState({ typingChecking: "false", suggestions: [], highlightedIndex: 0 });
this.state.suggestionCallback.dispatch({
type: 'WEB_CHAT/SEND_MESSAGE',
payload: {
text: newValue
}
});
await this.setState({ typingChecking: "true" });
}
getSuggestionCss(index) {
var HIGHLIGHTED_CSS = "HIGHLIGHTED_CSS";
var SUGGESTION_CSS = "SUGGESTION_CSS";
return index === this.state.highlightedIndex ? HIGHLIGHTED_CSS : SUGGESTION_CSS;
}
handleClose(elmnt) {
var x = document.getElementsByClassName("autocomplete-items");
for (var i = 0; i < x.length; i++) {
if (elmnt !== x[i]) {
x[i].parentNode.removeChild(x[i]);
}
}
}
async componentDidMount() {
try {
await this.handleTokenGeneration();
const store =
window.WebChat.createStore(
{},
({ getState }) => next => action => {
this.state.directLine.connectionStatus$
.subscribe(connectionStatus => {
if (connectionStatus === ConnectionStatus.ExpiredToken) {
console.log("expired");
}
if (action.type === 'WEB_CHAT/SET_SEND_BOX') {
const val = action.payload.text;
if (this.state.typingChecking === "true") {
this.setState({
highlightedIndex: -1,
});
console.log(this.state.typingChecking);
this.handleSuggestion(val, store);
}
}
if (action.type === 'DIRECT_LINE/DISCONNECT_FULFILLED') {
console.log("final" + connectionStatus);
console.log("finalexpired" + ConnectionStatus.ExpiredToken);
console.log("final");
this.handleTokenGeneration();
}
});
return next(action)
}
);
this.setState({ storeValue: store });
} catch (error) {
console.log("error in fetching token");
console.log(error);
}
this.state.directLine.activity$
.filter(activity => activity.type === 'message')
.subscribe(function (activity) {
//console.log("oooooooooooooooooooooo");
}
// message => console.log("received message ", message.text)
);
}
handleSaveFeedback(ans) {
// console.log(this.state.conversationId);
// console.log(this.state.feedBack);
var userID = "C94570";
var feedbackmsg = this.state.value;
var feedbacktype = this.state.feedBack;
var convId = this.state.conversationId;
fetch('api/Feedback/SaveFeedback',
{
method: "POST",
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ Uid: userID, FeedbackMessage: feedbackmsg, Convid: convId, FeedbackType: feedbacktype })
}).
then(response => response.text())
.then(data => {
console.log(data.getResult);
});
this.setState({ value: '' });
}
feedback(ans) {
this.setState({ feedBack: ans });
if (ans === "Send") {
this.handleSaveFeedback(ans);
}
else if (ans === "Yes") {
this.setState({ popupContent: "How was your experience?" });
// console.log(this.state.value)
}
else if (ans === "No") {
this.setState({ popupContent: "What went wrong?" });
// console.log(this.state.value)
}
}
handleChange = (event) => {
this.setState({ value: event.target.value });
}
styleOptions = {
bubbleBackground: 'rgba(0, 0, 255, .1)',
bubbleFromUserBackground: 'rgba(0, 255, 0, .1)',
botAvatarInitials: 'DIA',
userAvatarInitials: 'ME'
}
render() {
if (!this.state.view) {
return
<div />
} else {
const filteredSuggestions = this.state.suggestions.filter(
suggestion =>
suggestion.toLowerCase().indexOf(this.state.suggestionTypedText.toLowerCase())
> -1
);
// console.log(this.state.view);
return (
<div className="react-container webchat" >
<div onKeyDown={this.handleKeyDown.bind(this)}>
<div >
<ReactWebChat styleOptions={this.styleOptions} directLine={this.state.directLine} webSocket={true} userID='C94570' username='Thomas' store={this.state.storeValue} sendTypingIndicator={true} />
</div>
</div>
<div className="SuggestionParent" id="Suggestion1">
{this.state.suggestions.map((suggestion, index) => (
<div className={this.getSuggestionCss(index)} key={index} onClick={this.handleSuggestionClick} >
{suggestion
.toLowerCase()
.startsWith(this.state.suggestionTypedText) ? (
<div>
<b>{this.state.suggestionTypedText}</b>
{suggestion
.toLowerCase()
.replace(this.state.suggestionTypedText, "")}
</div>
) : (
<div dangerouslySetInnerHTML={this.getSuggestionHtml(suggestion)} />
)}
</div>
))}
</div>
<footer className="chat-footer" >
<div className="foot-footer">
Was I helpful ?
<span className="feedback" onClick={() => this.feedback("Yes")} >Yes</span><span>|</span><span className="feedback" onClick={() => this.feedback("No")}>No</span>
{
this.state.feedBack === "Yes" || this.state.feedBack === "No" ?
(
<div className="dialog" id="myform">
<div id="textfeedback">
<span id="closeFeedback" onClick={() => this.feedback("Close")}>X</span>
<p>{this.state.popupContent}</p>
<input type="text" id="feedbacktxtbox" required name="textfeedback" placeholder="Pleasure to hear from u!"
onChange={this.handleChange}
value={this.state.value} />
<button type="button" id="btnfeedback" onClick={() => this.feedback("Send")}>send</button>
</div>
</div>
) : null
}
</div>
</footer>
</div>
);
}
}
}
The chat input box is called the send box in Web Chat. Clearing the send box is just setting the send box with an empty string. This is done automatically when you click on the send button normally. You can see in the submit send box saga that submitting the send box means performing two actions: sending the message and setting the send box.
if (sendBoxValue) {
yield put(sendMessage(sendBoxValue.trim(), method, { channelData }));
yield put(setSendBox(''));
}
This means that if you use the SUBMIT_SEND_BOX action then the send box will be cleared automatically. Of course, if you want that to work with your autocomplete component then you'll need to set the send box with the autocompleted text before you submit it. Your other option is to just use the SET_SEND_BOX action with an empty string after you send the message.

Object is possibly 'undefined' in Vuex mutation with TypeScript

I'm learning Vue.js with Vuex and TypeScript, in the application i'm building i came across the error "Object is possibly 'undefined'" in the Vuex Store.
The error happens in the "newCard" mutation in this line:
state.board.lists.find(list => list.id === idList).cards.unshift(card)
The complete store code:
const state: BoardState = {
board: {
id: "",
name: "",
idProject: "",
closed: false,
lists: []
}
};
const getters: GetterTree<BoardState, {}> = {
getBoard: state => state.board
};
const mutations: MutationTree<BoardState> = {
setBoard: (state, board) => (state.board = board),
newList: (state, list) => state.board.lists.unshift(list),
newCard: (state, { card, idList }) =>
state.board.lists.find(list => list.id === idList).cards.unshift(card)
};
const actions: ActionTree<BoardState, {}> = {
async fetchBoard({ commit }) {
const response = await axios.post("https://app.fakejson.com/q", json);
commit("setBoard", response.data);
},
async addList({ commit }, list) {
const response = await axios.post("https://app.fakejson.com/q", {
token: "oplF0L7vj1Ial4cRqtx9DA",
data: list
});
commit("newList", response.data);
},
async addCard({ commit }, { card, idList }) {
const response = await axios.post("https://app.fakejson.com/q", {
token: "oplF0L7vj1Ial4cRqtx9DA",
data: card
});
commit("newCard", response.data, idList);
}
};
TypeScript types:
// Store
export interface BoardState {
board: Board;
}
// Models
export interface Board {
id: String;
name: String;
idProject: String;
closed: Boolean;
lists: List[];
}
export interface List {
id: String;
name: String;
idBoard: String;
closed: Boolean;
cards: Card[];
}
export interface Card {
id: String;
name: String;
idList: String;
closed: Boolean;
}
The response data of the board state is like this:
{
"id":"1",
"name":"Tasks",
"idProject":"1",
"closed":false,
"lists":[
{
"id":"1",
"name":"To Do",
"idBoard":"1",
"closed":false,
"cards":[
{
"id":"1",
"idList":"1",
"name":"Card 1",
"closed":false
},
{
"id":"2",
"idList":"1",
"name":"Card 2",
"closed":false
}
]
}
]
}
state.board.lists.find(list => list.id === idList).cards.unshift(card)
The specific list may not be found. So you won't be able to pick cards from it.
const list = state.board.lists.find(list => list.id === idList)
if (!list) {
// do something
return
}
// list found so return
return list.cards.unshift(card)

Accessing nested object

I'm having some trouble accessing the properties in the nested object. I've tried:
<p>{this.state.post.user.firstName}</p>
<p>{this.state.post.comments[0].user.firstName}</p>
Both lines don't not work, only <p>{this.state.post.date}</p> works.
Component:
state = {
post: {}
}
async componentDidMount() {
const { post_id } = this.props.match.params;
const response = await axios.get(`/posts/${post_id}`);
this.setState({
post: response.data
})
}
render() { return( ...... )}
Here's an example of my json:
{
"date": "2018",
"user": { "firstName": "Some Name" },
"comments": [
{
"body": "here's my comment."
"user": {
"firstName": "Some Name",
"lastName": "Some Lastname"
}
},
{......}
]
}
The error I'm getting:
TypeError: Cannot read property 'firstName' of undefined
TypeError: Cannot read property '0' of undefined
You are most likely getting these errors because you are not taking into consideration that post is initially an empty object, which will cause this.state.post.user.firstName and this.state.post.comments[0] to throw an error.
You could do this instead:
class MyComponent extends React.Component {
state = {
post: null
}
async componentDidMount() {
const { post_id } = this.props.match.params;
const response = await axios.get(`/posts/${post_id}`);
this.setState({
post: response.data
});
}
render() {
const { post } = this.state;
return post ? (
<div>
<p>{post.user.firstName}</p>
<p>{post.comments[0].user.firstName}</p>
<p>{post.date}</p>
</div>
) : null;
}
}

Why does vue.js alter my JSON data?

I want to return data from my API and display it in a vue.js project.
The data is:
{
"pages":[
{
"id":3,
"slug":"over-mij",
"updated_at":"2017-12-25T11:16:21+01:00",
"created_at":"2017-12-25T10:56:21+01:00",
"title":"Over mij",
"content":""
},
{
"id":6,
"slug":"mijn-cv",
"updated_at":"2017-12-25T11:07:29+01:00",
"created_at":"2017-12-25T11:07:29+01:00",
"title":"Mijn cv",
"content":null
}
],
"current_user":null
}
Then I'm using vue-resource to load the data from my API page in a seperate module of vuex:
const actions = {
initPages({commit}) {
Vue.resource('pages').get({}).then(function(response) {
if (response) {
response.json().then(data => {
state.pages = data;
});
}
});
}
}
The problem however is when I check what's inside the state.pages, this contains:
{
"pages": {
"pages": [
{
"id": 3,
"slug": "over-mij",
"updated_at": "2017-12-25T11:16:21+01:00",
"created_at": "2017-12-25T10:56:21+01:00",
"title": "Over mij",
"content": ""
},
{
"id": 6,
"slug": "mijn-cv",
"updated_at": "2017-12-25T11:07:29+01:00",
"created_at": "2017-12-25T11:07:29+01:00",
"title": "Mijn cv",
"content": null
}
],
"current_user": null
}
}
For some weird reason my JSON response is altered, I've already tried setting state.pages to data.pages and this just eliminates the first pages object but not the second one.
When I set my state.pages to data.pages[0] it does work, does anyone know why this is happening?
Even when I use mutations, I still have the same issue:
module of store.js:
import Vue from 'vue';
const state = {
pages: []
}
const mutations = {
'setPages' (state, pages) {
state.pages = pages;
}
}
const getters = {
pages(state) {
return state.pages;
},
page(state) {
return keyword => state.pages.find(function(page) {
return page.slug === keyword;
});
}
}
const actions = {
initPages({commit}) {
Vue.resource('pages').get({}).then(function(response) {
if (response) {
response.json().then(data => {
commit('setPages', data.pages);
});
}
});
}
}
export default {
state,
getters,
mutations,
actions
}

Reactjs: Why my props aren't being updated?

I need to update my props in order to render new data.
I have a view with a list of dealers for a casino game. That list is OK, the problem comes up when you try to add a new dealer, the dealer doesn't display in the view, yo have to reload the page in order to see the new change.
Let me show you my code starting in the actions
action
class CreateDealersActions {
constructor () {
this.generateActions('createDealerSuccess');
}
createDealer (data) {
const that = this;
that.dispatch();
axios.post(`${API_ENDPOINT}/create-dealer/create-dealer`, data)
.then(function success (response) {
that.actions.createDealerSuccess({response});
})
}
}
store
class GetDealersStore {
constructor () {
this.state = {
dealerData : null,
};
}
#bind(GetDealersActions.dealerDataSuccess)
dealerDataSuccess (data) {
this.setState({
dealerData : data,
});
}
#bind(CreateDealersActions.createDealerSuccess)
createDealerSuccess (data) {
this.setState({
dealerData : data,
});
}
}
the dealerDataSuccess() is the function I call when the view loads in order to render the list of dealers, and createDealerSuccess() is the one called when you attempt to add a new dealer.
here you will see what every function returns
if you put in dealerDataSuccess() console.log(JSON.stringify(data));
{"dealersData": [{
"DealerId":"1",
"DealerName":"Carmen",
"NickName":"Carmen",
"Picture":"url",
"Active":"1",
"LegalId":"13",
"TypeId":"1"}
]}
but if you put in createDealerSucess() console.log(JSON.stringify(data)); it returns something like this:
{
"response": {
"data": {
"success": "New dealer successfully inserted."
},
"status": 200,
"statusText": "OK",
"headers": {
"content-type": "application/json; charset=utf-8"
},
"config": {
"method": "post",
"headers": {
"Content-Type": "application/json;charset=utf-8"
},
"transformRequest": [
null
],
"transformResponse": [
null
],
"url": "http://localhost:1102/services/create-dealer/create-dealer",
"data": {
"DealerName": "my Name",
"CardId": "1221",
"NickName": "newName",
"Picture": "url",
"Active": "1",
"LegalId": "321321",
"TypeId": "1"
}
}
}
}
the component code
component
#connectToStores
export default class Dealers extends Component {
static contextTypes = {
router : React.PropTypes.func,
}
constructor (props) {
super(props);
this.state = {}
}
componentWillMount () {
GetDealersActions.getDealers();
}
static getStores () {
return [ GetDealersStore ];
}
static getPropsFromStores () {
return {
...GetDealersStore.getState(),
}
}
render () {
return (<html for component>);
}
_addDealer = () => {
CreateDealersActions.createDealer({
DealerName : this.refs.DealerName.getValue(),
CardId : this.refs.CardId.getValue(),
});
}
}
now in the component part there is componentWillMount(), if you put console.log(JSON.stringify(this.props)); it returns
{"params":{},"query":{},"dealerData":null}
and if you put in _addDealer console.log(JSON.stringify(this.props)); where it suppose to add the new dealer you get the whole props but without the last dealer you add, so you have to refresh the page in order to see the new dealer in the view/screen.
What do you think is going on here ?
PS: if you similar question about this from me, take into account that in the other question I was 2 using different stores, here I am using just one
EDIT
the Dealers component is within a tab named management, which is this one:
const menuItems = [
{ route : 'dealers', text : 'Dealers' },
{ route : 'game-info', text : 'Game Info' },
{ route : 'player-info', text : 'Players Info' },
{ route : 'money', text : 'Money' }
];
export default class Management extends React.Component {
static propTypes = {
getActivePage : React.PropTypes.func,
menuItems : React.PropTypes.arrayOf(React.PropTypes.object),
}
static contextTypes = {
router : React.PropTypes.func,
}
render () {
return (
<div>
<TabsMainMenu menuItems={menuItems} getActivePage={this._getActivePage} />
<RouteHandler />
</div>
);
}
_getActivePage = () => {
for (const i in menuItems) {
if (this.context.router.isActive(menuItems[i].route)) return parseInt(i, 10);
}
}
}

Categories

Resources