My code pass in a search term and the promise api call returns one record and the data format is as below:
` json api data
0:
{
id:"aff3b4fa-bdc0-47d1-947f-0163ff5bea06"
keyword: somekeyword
URL:"mypage.html"
}
I need to retrieve the URL value, so I try to get URL by using response.data[0].URL. But I receive the error "Unhandled Rejection (TypeError): response.data[0] is undefined". How do I get the URL value? Thanks.
` autocomplete.js
export class Autocomplete extends Component {
state = {
activeSuggestion: 0,
filteredSuggestions: [],
showSuggestions: false,
userInput: "",
suggestions: [],
results: [],
URL: "",
};
componentDidMount() {
this.GetPrograms();
const { userInput } = this.state;
//this.runSearch();
}
GetPrograms = () => {
axios
.get("https://mydomain/GetPrograms/")
.then((response) => {
this.setState({ suggestions: response.data });
});
};
runSearch = async () => {
const response = await axios.get(
"https://mydomain/api/get",
{
params: {
searchTerm: this.state.userInput,
},
}
);
let results = response.data;
console.log("response", results);
this.setState({ results: results, URL: response.data[0].URL });
window.location.href =
"https://mydomain/" + this.state.URL;
};
onChange = (e) => {
const { suggestions } = this.state; //this.props;
const userInput = e.currentTarget.value;
const filteredSuggestions = suggestions.filter(
(suggestion) =>
suggestion.toLowerCase().indexOf(userInput.toLowerCase()) > -1
);
this.setState({
activeSuggestion: 0,
filteredSuggestions,
showSuggestions: true,
userInput: e.currentTarget.value,
});
};
onClick = (e) => {
this.setState({
activeSuggestion: 0,
filteredSuggestions: [],
showSuggestions: false,
userInput: e.currentTarget.innerText,
});
this.onSearch();
console.log(
"child component clicked and value=" + e.currentTarget.innerText
);
};
onKeyDown = (e) => {
const { activeSuggestion, filteredSuggestions } = this.state;
if (e.keyCode === 13) {
this.setState({
activeSuggestion: 0,
showSuggestions: false,
userInput: filteredSuggestions[activeSuggestion],
});
} else if (e.keyCode === 38) {
if (activeSuggestion === 0) {
return;
}
this.setState({ activeSuggestion: activeSuggestion - 1 });
} else if (e.keyCode === 40) {
if (activeSuggestion - 1 === filteredSuggestions.length) {
return;
}
this.setState({ activeSuggestion: activeSuggestion + 1 });
}
//this.setState({ searchTerm: e.currentTarget.value });
console.log("userinput:" + this.state.userInput);
};
render() {
const {
onChange,
onClick,
onKeyDown,
onKeyPress,
state: {
activeSuggestion,
filteredSuggestions,
showSuggestions,
userInput,
},
} = this;
let suggestionsListComponent;
if (showSuggestions && userInput) {
if (filteredSuggestions.length) {
suggestionsListComponent = (
<ul class="suggestions">
{filteredSuggestions.map((suggestion, index) => {
let className;
if (index === activeSuggestion) {
className = "";
}
return (
<li key={suggestion} onClick={onClick}>
{suggestion}
</li>
);
})}
</ul>
);
} else {
suggestionsListComponent = (
<div class="no-suggestions">
<em>No suggestions</em>
</div>
);
}
}
return (
<div>
<input
id="search-box"
placeholder="Search..."
type="search"
onChange={onChange}
onKeyDown={onKeyDown}
value={userInput}
/>
{suggestionsListComponent}
</div>
);
}
}
export default Autocomplete;
`
The api call returns 0 record that causes the error.
Related
I am new to React and It really interesting to work on it. As per my current application which is a Quiz app, If user selects any of the options it should change the background color to red or green. I am using the semantic UI and to the menu item, I am passing the data with an on-click event where I am storing the selected answer from the user. But I am unable to change the color wrt the correct answer or wrong answer. Here is the code.
import React, { Component } from 'react';
import {
Container,
Segment,
Item,
Divider,
Button,
Icon,
Message,
Menu,
Header
} from 'semantic-ui-react';
import Swal from 'sweetalert2';
import Loader from '../Loader';
import Countdown from '../Countdown';
import Result from '../Result';
import Offline from '../Offline';
import he from 'he';
import { getRandomNumber } from '../../utils/getRandomNumber';
class Quiz extends Component {
constructor(props) {
super(props);
this.state = {
quizData: null,
isLoading: true,
questionIndex: 0,
correctAnswers: 0,
userSlectedAns: null,
quizIsCompleted: false,
questionsAndAnswers: [],
isOffline: false,
bgColor: ""
};
this.timeTakesToComplete = undefined;
this.setData = this.setData.bind(this);
this.handleItemClick = this.handleItemClick.bind(this);
this.handleNext = this.handleNext.bind(this);
this.timesUp = this.timesUp.bind(this);
this.timeAmount = this.timeAmount.bind(this);
this.renderResult = this.renderResult.bind(this);
this.retakeQuiz = this.retakeQuiz.bind(this);
this.startNewQuiz = this.startNewQuiz.bind(this);
this.resolveError = this.resolveError.bind(this);
}
componentDidMount() {
const { API } = this.props;
fetch(API)
.then(respone => respone.json())
.then(result => setTimeout(() => this.setData(result.results), 1000))
.catch(error => setTimeout(() => this.resolveError(error), 1000));
}
resolveError(error) {
if (!navigator.onLine) {
this.setState({ isOffline: true });
console.log('Connection problem');
} else {
this.setState({ isOffline: true });
console.log('API problem ==> ', error);
}
}
setData(results) {
if (results.length === 0) {
const message =
"The API doesn't have enough questions for your query<br />" +
'(ex. Asking for 50 questions in a category that only has 20).' +
'<br /><br />Please change number of questions, difficulty level ' +
'or type of questions.';
return Swal.fire({
title: 'Oops...',
html: message,
type: 'error',
timer: 10000,
onClose: () => {
this.props.backToHome();
}
});
}
const quizData = results;
const { questionIndex } = this.state;
const outPut = getRandomNumber(0, 3);
const options = [...quizData[questionIndex].incorrect_answers];
options.splice(outPut, 0, quizData[questionIndex].correct_answer);
this.setState({ quizData, isLoading: false, options, outPut });
}
handleItemClick(e, { name }) {
const {
userSlectedAns,
quizData,
questionIndex,
} = this.state;
this.setState({ userSlectedAns: name });
console.log(name);
if (userSlectedAns === he.decode(quizData[questionIndex].correct_answer)) {
this.state.active = 'green';
}
}
handleNext() {
const {
userSlectedAns,
quizData,
questionIndex,
correctAnswers,
questionsAndAnswers
} = this.state;
let point = 0;
if (userSlectedAns === he.decode(quizData[questionIndex].correct_answer)) {
point = 1;
}
questionsAndAnswers.push({
question: he.decode(quizData[questionIndex].question),
user_answer: userSlectedAns,
correct_answer: he.decode(quizData[questionIndex].correct_answer),
point
});
if (questionIndex === quizData.length - 1) {
this.setState({
correctAnswers: correctAnswers + point,
userSlectedAns: null,
isLoading: true,
quizIsCompleted: true,
questionIndex: 0,
options: null,
questionsAndAnswers
});
return;
}
const outPut = getRandomNumber(0, 3);
const options = [...quizData[questionIndex + 1].incorrect_answers];
options.splice(outPut, 0, quizData[questionIndex + 1].correct_answer);
this.setState({
correctAnswers: correctAnswers + point,
questionIndex: questionIndex + 1,
userSlectedAns: null,
options,
outPut,
questionsAndAnswers
});
}
timesUp() {
this.setState({
userSlectedAns: null,
isLoading: true,
quizIsCompleted: true,
questionIndex: 0,
options: null
});
}
timeAmount(timerTime, totalTime) {
this.timeTakesToComplete = {
timerTime,
totalTime
};
}
renderResult() {
setTimeout(() => {
const { quizData, correctAnswers, questionsAndAnswers } = this.state;
const { backToHome } = this.props;
const resultRef = (
<Result
totalQuestions={quizData.length}
correctAnswers={correctAnswers}
timeTakesToComplete={this.timeTakesToComplete}
questionsAndAnswers={questionsAndAnswers}
retakeQuiz={this.retakeQuiz}
backToHome={backToHome}
/>
);
this.setState({ resultRef, questionsAndAnswers: [] });
}, 2000);
}
retakeQuiz() {
const { quizData, questionIndex } = this.state;
const outPut = getRandomNumber(0, 3);
const options = [...quizData[questionIndex].incorrect_answers];
options.splice(outPut, 0, quizData[questionIndex].correct_answer);
this.setState({
correctAnswers: 0,
quizIsCompleted: false,
startNewQuiz: true,
options,
outPut
});
}
startNewQuiz() {
setTimeout(() => {
this.setState({ isLoading: false, startNewQuiz: false, resultRef: null });
}, 1000);
}
render() {
const {
quizData,
questionIndex,
options,
userSlectedAns,
isLoading,
quizIsCompleted,
resultRef,
startNewQuiz,
isOffline
// outPut,
// correctAnswers,
} = this.state;
// console.log(userSlectedAns);
// console.log(questionIndex, outPut);
// console.log('Score ==>', correctAnswers);
if (quizIsCompleted && !resultRef) {
this.renderResult();
// console.log('Redirecting to result');
}
if (startNewQuiz) {
this.startNewQuiz();
}
return (
<Item.Header>
{!isOffline && !quizIsCompleted && isLoading && <Loader />}
{!isOffline && !isLoading && (
<Container>
<Segment>
<Item.Group divided>
<Item>
<Item.Content>
<Item.Extra>
<Header as="h1" block floated="left">
<Icon name="info circle" />
<Header.Content>
{`Question No.${questionIndex + 1} of ${
quizData.length
}`}
</Header.Content>
</Header>
<Countdown
countdownTime={this.props.countdownTime}
timesUp={this.timesUp}
timeAmount={this.timeAmount}
/>
</Item.Extra>
<br />
<Item.Meta>
<Message size="huge" floating>
<b>{`Q. ${he.decode(
quizData[questionIndex].question
)}`}</b>
</Message>
<br />
<Item.Description>
<h3>Please choose one of the following answers:</h3>
</Item.Description>
<Divider />
<Menu vertical fluid size="massive">
{options.map((option, i) => {
let letter;
switch (i) {
case 0:
letter = 'A.';
break;
case 1:
letter = 'B.';
break;
case 2:
letter = 'C.';
break;
case 3:
letter = 'D.';
break;
default:
letter = i;
break;
}
const decodedOption = he.decode(option);
return (
<Menu.Item
key={decodedOption}
name={decodedOption}
active={userSlectedAns === decodedOption}
onClick={this.handleItemClick}
// style={{backgroundColor: this.state.bgColor }}
>
<b style={{ marginRight: '8px' }}>{letter}</b>
{decodedOption}
</Menu.Item>
);
})}
</Menu>
</Item.Meta>
<Divider />
<Item.Extra>
<Button
primary
content="Next"
onClick={this.handleNext}
floated="right"
size="big"
icon="right chevron"
labelPosition="right"
disabled={!userSlectedAns}
/>
</Item.Extra>
</Item.Content>
</Item>
</Item.Group>
</Segment>
<br />
</Container>
)}
{quizIsCompleted && !resultRef && (
<Loader text="Getting your result." />
)}
{quizIsCompleted && resultRef}
{isOffline && <Offline />}
</Item.Header>
);
}
}
export default Quiz;
I checked your handleItemClick function and found that you're mutating the state directly. You should use setState() to update the state, that's the basic thing about React's state mutation.
Please change the following:
if (userSlectedAns === he.decode(quizData[questionIndex].correct_answer)) {
this.state.active = 'green';
}
To this way:
if (userSlectedAns === he.decode(quizData[questionIndex].correct_answer)) {
this.setState({
active: 'green'
});
}
what am I doing wrong
I'm making a rest request but I'm not getting the data
I'm having the 403 error
is there any parameter missing
I tested the api on insomnia and it's working
the data appears on the console but does not appear on the screen
Code API below
How can I Solve this?
I am New With React
import axios from 'axios';
import Utils from '../atendimento/utils';
const URL = `${Utils.ngrok_service}/protocol/generate`;
const protocolGet = (clientCode, _success, _error) => {
if (!!clientCode) {
const options = {
headers: { 'Content-Type': 'application/json;charset=UTF-8' },
};
const Code = {
codigoCliente: String(clientCode).split(' ').join(''),
};
axios
.post(URL, Code, options)
.then((response) => {
const data = response.data;
if (Object.keys(data).length > 0) {
if (typeof _success === 'function') _success(data);
} else {
if (typeof _error === 'function') {
_error({
code: 404,
message: 'Falha ao gerar um protocolo.',
});
}
}
})
.catch((error) => {
if (typeof _error === 'function') {
_error({
code: 400,
message: 'Falha ao gerar um protocolo.',
});
}
});
}
};
export default protocolGet;
Code JSX Bellow:
class SelectTabs extends Component {
constructor ( props ) {
super( props );
this.state = {
options: [],
cusProtocol:"",
isReady: false
};
this.loadTabs = this.loadTabs.bind( this );
this.makeOptions = this.makeOptions.bind( this );
}
componentDidMount ( ) {
console.log('[SelectTabs] rendered with props: ', this.props );
this.loadTabs();
}
loadTabs ( ) {
protocolGet( "123245",cusProtocol => {
console.log('[SelectProtocol] cusProtocol: ', cusProtocol );
this.setState({ cusProtocol });
}, error => {
console.log('[SelectProtocol] Não foi possível consultar o serviço: ');
console.log( error );
});
tabGet( options => {
console.log('[SelectTabs] options: ', options );
this.setState({ options });
}, error => {
console.log('[SelectTabs] Não foi possível consultar o serviço: ');
console.log( error );
});
}
makeOptions ( object ) {
const options = object.map( data => {
return {
value: data,
label: data
}
});
return options;
}
render ( ) {
const $Task = this.props.task;
const selectProps = {
isRtl: false,
isMulti: false,
isClearable: false,
isSearchable: false,
placeholder: 'Selecione',
noOptionsMessage: () => 'Aguarde...'
};
return (
<React.Fragment>
<SC.Container>
<SC.Title>Protocolo</SC.Title>
<SC.Input>
<TextareaAutosize disabled type="text" value={
this.state.cusProtocol
}/>
</SC.Input>
<SC.Title>Tabulação</SC.Title>
<Select
{ ...selectProps }
options={ this.makeOptions( this.state.options ) }
onChange={ event => {} }
/>
</SC.Container>
</React.Fragment>
);
I want my bot to send the message when i click on the desired suggestion. i.e. i want the message to be sent - when i click on the suggestion or by selecting the suggestion using arrow keys and then pressing enter . But as of now, if i click or select the suggestion using arrow keys - the suggestion value comes to the text box and then i have to press enter to send the message. I just want to change that.
Any help would be greatly appreciated
My code is as follows,
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()
});
var totCount = data.az_search;
console.log("kkkkkk" + totCount);
var myNode = document.getElementById('Suggestion1');
}
}
getSuggestionCss(index) {
var HIGHLIGHTED_CSS = "HIGHLIGHTED_CSS";
var SUGGESTION_CSS = "SUGGESTION_CSS";
console.log("jioouu" + this.state.highlightedIndex);
return index === this.state.highlightedIndex ? HIGHLIGHTED_CSS : SUGGESTION_CSS;
}
moveHighlight(event, direction) {
event.preventDefault();
const { suggestions, highlightedIndex=-1 } = this.state;
if (!suggestions.length) return;
let newIndex = (highlightedIndex + direction + suggestions.length) % suggestions.length;
console.log("lokkkk" + direction)
if (newIndex !== highlightedIndex) {
console.log("kkkkkkkkkkkkkkkkkkk")
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)
if (this.keyDownHandlers[event.key])
this.keyDownHandlers[event.key].call(this, event)
}
async handleSuggestionClick(event) {
await this.applySuggestion(event.currentTarget.textContent);
}
async applySuggestion(newValue) {
await this.setState({ typingChecking: "false", suggestions: [], highlightedIndex: 0 });
this.state.suggestionCallback.dispatch({
type: 'WEB_CHAT/SET_SEND_BOX',
payload: {
text: newValue,
}
});
await this.setState({ typingChecking: "true" });
}
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 => {
//console.log("connect" + connectionStatus);
//console.log("LOP" + ConnectionStatus.ExpiredToken);
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();
// fetch('api/TokenGenerationService/GetToken').then(conversation => this.state.directLine.reconnect(conversation))
}
});
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) {
var userID = "U92656";
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 });
}
render() {
if (!this.state.view) {
return <div />
} else {
const filteredSuggestions = this.state.suggestions.filter(
suggestion =>
suggestion.toLowerCase().indexOf(this.state.suggestionTypedText.toLowerCase()) > -1
);
return (
<div className="react-container webchat" >
<div onKeyDown={this.handleKeyDown.bind(this)}>
<div >
<ReactWebChat directLine={this.state.directLine} webSocket={true} userID='U92656' 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>
);
}
}
}
I am newbie to Reactjs and I am making a function to increase and decrease quantity. My code below:
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
quantity: 1,
show: true,
max:5,
min:0
};
}
IncrementItem = () => {
if(this.state.quantity > 9) {
}else {
this.setState({
quantity: this.state.quantity + 1
});
}
}
DecreaseItem = () => {
if(this.state.quantity <= 1) {
}else {
this.setState({ quantiy: this.state.quantity - 1 });
}
}
ToggleClick = () => {
this.setState({ show: !this.state.show });
}
render() {
return (
<div>
<button onClick={this.IncrementItem}>+</button>
<input className="inputne" value={this.state.quantity} />
<button onClick={this.DecreaseItem}>-</button>
</div>
);
}
I have problems are:
Browser appears an error :
Warning: Failed prop type: You provided a value prop to a form field without an onChange handler
I cannot change value in input from View.
Please let me know how to solve. Thank for your help.
There are two issues in this code:
There is no onChange handler. Read more on how to handle onChange listeners here
Using value from this.state.quantity to increment and decrement is bad practice because setState function is asynchronous.
You can use functional version of setState to get around this:
this.setState(prevState => {
if(prevState.quantity > 0) {
return {
quantity: prevState.quantity - 1
}
} else {
return null;
}
});
Code Snippet:
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
quantity: 1,
show: true,
max: 5,
min: 0
};
}
IncrementItem = () => {
this.setState(prevState => {
if(prevState.quantity < 9) {
return {
quantity: prevState.quantity + 1
}
} else {
return null;
}
});
}
DecreaseItem = () => {
this.setState(prevState => {
if(prevState.quantity > 0) {
return {
quantity: prevState.quantity - 1
}
} else {
return null;
}
});
}
ToggleClick = () => {
this.setState({
show: !this.state.show
});
}
handleChange = (event) => {
this.setState({quantity: event.target.value});
}
render() {
return ( <div>
<button onClick={this.IncrementItem}>+</button>
<input className="inputne" value={this.state.quantity} onChange={this.handleChange}/>
<button onClick = {this.DecreaseItem}>-< /button>
</div>
);
}
}
ReactDOM.render( < App / > , document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
You need to Update the value, add a onChange on Input field to do that.
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
quantity: 1,
show: true,
max:5,
min:0
};
}
IncrementItem = () => {
if(this.state.quantity > 9) {
}else {
this.setState({
quantity: this.state.quantity + 1
});
}
}
DecreaseItem = () => {
if(this.state.quantity <= 1) {
}else {
this.setState({ clicks: this.state.quantity - 1 });
}
}
ToggleClick = () => {
this.setState({ show: !this.state.show });
}
UpdateValue = (e) => {
this.setState({ quantity: e.target.value });
}
render() {
return (
<div>
<button onClick={this.IncrementItem}>+</button>
<input className="inputne" value={this.state.quantity} onChange={this.UpdateValue} />
<button onClick={this.DecreaseItem}>-</button>
</div>
);
}
Try this as well it may help you
class Counters extends Component {
state = {
counters: [
{ id: 1, value: 4, max: 15, min: 0, show: true },
{ id: 2, value: 0 }`enter code here`
]
};
handleIncrement = counter => {
const counters = [...this.state.counters];
const index = counters.indexOf(counter);
if (counters[index].value < counters[index].max) {
counters[index].value++;
}
this.setState({ counters });
};
handleDecrement = counter => {
const counters = [...this.state.counters];
const index = counters.indexOf(counter);
if (counters[index].value > counters[index].min) {
counters[index].value--;
}
this.setState({ counters });
};
handleDelete = counterId => {
const counters = this.state.counters.filter(c => c.id !== counterId);
this.setState({ counters });
};
render() {
return (
<div>
{this.state.counters.map(counter => (
<Counter
key={counter.id}
onDelete={this.handleDelete}
onIncrement={this.handleIncrement}
onDecrement={this.handleDecrement}
counter={counter}
/>
))}
</div>
);
}
}
export default Counters;
enter code here
i am new on ReactJS and i am trying to find the correct way to mix a props of a parent component with a normal string URL
in my Child component i have two props in my child component:
this.props.originalUrl = https://server.com
this.props.todayDate = "2018-08-16"
and i have a url lets say it is
let url = https://server.com/123/2018-08-16/blabla
what i want is to make it dynamic url like
let url = `${this.props.originalUrl }/123/${this.props.todayDate }/blabla`
But when i use
let url = `${this.props.originalUrl }/123/2018-08-16/blabla`
The console give me the correct URL that i want
https://server.com/123/2018-08-16/blabla
but with two props like this
let url = `${this.props.originalUrl }/123/${this.props.todayDate}/blabla`
the console give me
https://server.com/123//blabla without the date
How can i mix them currently ??
Note: when i use {this.props.todayDate} in the Child componenet return it is look work and rendered as 2018-08-16
this is the full code
import React, { Component } from 'react';
import { extend } from 'underscore';
import { translate, Trans} from 'react-i18next';
import axios from 'axios';
import { Alert } from 'react-alert'
import TableNav from './tableNav';
import Table from './table';
class TableContainer extends Component {
constructor(props) {
super(props);
this.state = {
sortBy: 'id',
filteredData: [],
checkedboxArray: [],
sortingOptions: [
'id'],
sortingDirection: {
'id': true,
},
data: [],
itemsPerPage: 20,
totalPages: '',
firstUrl: '',
previousUrl: '',
currentUrl: '',
nextUrl: '',
lastUrl: '',
totalItems:'',
currentPageNumber: '',
originalurl: `${this.props.cmsUrl}performances?eq(flyers.id,empty())>e(startDateTime,${this.props.todayDate})&sort(+startDateTime)`,
performancesSelected: [],
myItemsState: true
};
let url = this.state.originalurl;
axios.get(url, { withCredentials: true })
.then((response) => {
this.setState({
totalPages:response.data.pagination.pages,
totalItems:response.data.pagination.total,
currentPageNumber: response.data.pagination.page,
firstUrl:response.data.pagination.links.first,
previousUrl:response.data.pagination.links.previous,
currentUrl:response.data.pagination.links.current,
nextUrl:response.data.pagination.links.next,
lastUrl:response.data.pagination.links.last,
data:response.data.results,
});
});
this.getTotal = this.getTotal.bind(this);
this.onSelectChange = this.onSelectChange.bind(this);
this.onColumnClick = this.onColumnClick.bind(this);
this.filterData = this.filterData.bind(this);
this.sortData = this.sortData.bind(this);
this.checkedbox = this.checkedbox.bind(this);
this.nextPageFunc = this.nextPageFunc.bind(this);
this.previousPageFunc = this.previousPageFunc.bind(this);
this.firstpageFunc = this.firstpageFunc.bind(this);
this.lastpageFunc = this.lastpageFunc.bind(this);
}
getTotal() {
return this.state.data.length;
}
onSelectChange(e, option) {
if (option === 'sortBy') {
this.setState({ sortBy: e.target.value });
this.sortData(e.target.value, this.state.sortBy);
this.setState({ currentPage: 1});
} else {
this.setState({ itemsPerPage: e.target.value });
this.setState({ currentPage: 1});
}
}
onColumnClick(e) {
var clicked = e.target.getAttribute('class');
this.setState({ sortBy: clicked });
this.sortData(clicked, this.state.sortBy);
}
filterData() {
return this.state.data;
}
sortData(sortBy, previousSortBy) {
sortBy = sortBy.toLowerCase().replace(' ', '');
previousSortBy = previousSortBy.toLowerCase().replace(' ', '');
var ascending = this.state.sortingDirection[sortBy];
if (sortBy === previousSortBy) {
ascending = !ascending;
this.setState({ sortingDirection: extend(this.state.sortingDirection, { [sortBy]: ascending }) });
}
var data = this.state.data.sort(function(a, b) {
if(a[sortBy] < b[sortBy]) {
return ascending ? -1 : 1;
}
if(a[sortBy] > b[sortBy]) {
return ascending ? 1 : -1;
}
return 0;
});
this.setState({ data })
}
checkedbox(id){
let checkedboxArray = this.state.checkedboxArray;
let flyersAraay = this.state.data;
let performancesSelected = this.state.performancesSelected;
// if Selected ID are not in the checkedboxArray
if ( checkedboxArray.indexOf(id) === -1 ) {
checkedboxArray.push(id) ;
this.setState({checkedboxArray: checkedboxArray })
let selecObject = flyersAraay.find(function (xxx) { return xxx.id === id; });
performancesSelected.push(selecObject)
let data = JSON.stringify(performancesSelected)
sessionStorage.setItem( "Performances" , data)
}
// if Selected ID are in the checkedboxArray
else if ( checkedboxArray.indexOf(id) !== -1 ) {
let i = checkedboxArray.indexOf(id);
if (i !== -1) {
checkedboxArray.splice(i, 1);
performancesSelected.splice(i, 1);
this.setState({checkedboxArray: checkedboxArray })
let data = JSON.stringify(performancesSelected)
sessionStorage.setItem( "Performances" , data)
}
}
}
nextPageFunc() {
let StrUrl = JSON.stringify(this.state.nextUrl);
let smallUrl = StrUrl.split("external/").pop();
let editeUrl = this.props.cmsUrl + smallUrl;
let url = editeUrl;
axios.get(url, { withCredentials: true })
.then((response) => {
this.setState({
totalPages: response.data.pagination.pages,
totalItems: response.data.pagination.total,
currentPageNumber: response.data.pagination.page,
firstUrl: response.data.pagination.links.first,
previousUrl: response.data.pagination.links.previous,
currentUrl: response.data.pagination.links.current,
nextUrl: response.data.pagination.links.next,
lastUrl: response.data.pagination.links.last,
data: response.data.results,
});
});
}
previousPageFunc() {
let StrUrl = JSON.stringify(this.state.previousUrl);
let restUrl = StrUrl.split("external/").pop();
let editeUrl = this.props.cmsUrl + restUrl;
let url = editeUrl;
axios.get(url, { withCredentials: true })
.then((response) => {
this.setState({
totalPages: response.data.pagination.pages,
totalItems: response.data.pagination.total,
currentPageNumber: response.data.pagination.page,
firstUrl: response.data.pagination.links.first,
previousUrl: response.data.pagination.links.previous,
currentUrl: response.data.pagination.links.current,
nextUrl: response.data.pagination.links.next,
lastUrl: response.data.pagination.links.last,
data: response.data.results,
});
});
}
firstpageFunc() {
let StrUrl = JSON.stringify(this.state.firstUrl);
let restUrl = StrUrl.split("external/").pop();
let editeUrl = this.props.cmsUrl + restUrl;
let url = editeUrl;
axios.get(url, { withCredentials: true })
.then((response) => {
this.setState({
totalPages: response.data.pagination.pages,
totalItems: response.data.pagination.total,
currentPageNumber: response.data.pagination.page,
firstUrl: response.data.pagination.links.first,
previousUrl: response.data.pagination.links.previous,
currentUrl: response.data.pagination.links.current,
nextUrl: response.data.pagination.links.next,
lastUrl: response.data.pagination.links.last,
data: response.data.results,
});
});
}
lastpageFunc() {
let StrUrl = JSON.stringify(this.state.lastUrl);
let smallUrl = StrUrl.split("external/").pop();
let editeUrl = this.props.cmsUrl + smallUrl;
let url = editeUrl;
axios.get(url, { withCredentials: true })
.then((response) => {
this.setState({
totalPages: response.data.pagination.pages,
totalItems: response.data.pagination.total,
currentPageNumber: response.data.pagination.page,
firstUrl: response.data.pagination.links.first,
previousUrl: response.data.pagination.links.previous,
currentUrl: response.data.pagination.links.current,
nextUrl: response.data.pagination.links.next,
lastUrl: response.data.pagination.links.last,
data: response.data.results,
});
});
}
myItemsCheckbox(e) {
let state = this.state.myItemsState
if ( state === false ) {
axios.get( `${this.props.cmsUrl}performances?eq(flyers.id,empty())>e(startDateTime,2018-08-16)&sort(+startDateTime)`, { withCredentials: true })
.then((response) => {
this.setState({
totalPages:response.data.pagination.pages,
totalItems:response.data.pagination.total,
currentPageNumber: response.data.pagination.page,
firstUrl:response.data.pagination.links.first,
previousUrl:response.data.pagination.links.previous,
currentUrl:response.data.pagination.links.current,
nextUrl:response.data.pagination.links.next,
lastUrl:response.data.pagination.links.last,
data:response.data.results,
});
});
this.setState({ myItemsState: true})
}
else if ( state === true ) {
axios.get( this.props.cmsUrl+"performances", { withCredentials: true })
.then((response) => {
this.setState({
totalPages:response.data.pagination.pages,
totalItems:response.data.pagination.total,
currentPageNumber: response.data.pagination.page,
firstUrl:response.data.pagination.links.first,
previousUrl:response.data.pagination.links.previous,
currentUrl:response.data.pagination.links.current,
nextUrl:response.data.pagination.links.next,
lastUrl:response.data.pagination.links.last,
data:response.data.results,
});
});
this.setState({ myItemsState: false })
}
}
render() {
const { itemsPerPage, totalPages, data, currentPageNumber, totalItems, firstUrl, previousUrl, currentUrl, nextUrl, lastUrl, checkedboxArray } = this.state;
return (
<div>
<div className="myItemsButton">
<Alert>{ alert => (
<span className="btn myItemsSpan ">
<input
className="inputSelect"
defaultChecked={this.state.myItemsState}
onChange={ () => { { alert.show('You have changed the Items order' )} ; this.myItemsCheckbox() } }
type="checkbox"
id="xd"
name="cc"
/>
<label htmlFor="xd"><span></span></label>
myItems
</span>
)}
</Alert>
</div>
<TableNav
itemsPerPage={itemsPerPage}
totalPages={totalPages}
data={data}
currentPageNumber={currentPageNumber}
totalItems={totalItems}
firstpageFunc={this.firstpageFunc}
previousPageFunc={this.previousPageFunc}
nextPageFunc={this.nextPageFunc}
lastpageFunc={this.lastpageFunc}
firstUrl={firstUrl}
previousUrl={previousUrl}
currentUrl={currentUrl}
nextUrl={nextUrl}
lastUrl={lastUrl} />
<Table
onColumnClick={this.onColumnClick}
checkedbox={this.checkedbox}
data={data}
checkedboxArray={checkedboxArray}
filteredData={this.filterData()} />
{ this.state.data.length === 0 && (
<table className="table noResultsTable bordered table-hover table-dark">
<tbody>
<tr>
<td>
<div className="col-12 text-center noResults">
{/* <i className="fas fa-cog"></i> */}
<i className="fa fa-exclamation-triangle"></i>
<span className="resultsText"><Trans>No results found</Trans> {this.props.todayDate} ...</span>
</div>
</td>
</tr>
</tbody>
</table>
)}
</div>
);
}
}
export default translate('translations')(TableContainer);
in the last <span className="resultsText">i can read the time as