Value not incemented by one?

I have created a survey form with formik in react hooks. Initial state values of react variables are fetched by the database. I have created an icon button that increments the value of votes by one onclick. The problem is whenever I have clicked on icon value not incremented by.

Initial state before clicking on icon

result after clicking on icon

I have attached the above screenshot of the output before and after a click on the button.

Code:

// @ts-ignore
import React, { useState, useEffect } from 'react';
import { Formik, Form, Field } from 'formik';
import {
Typography,
Button,
Grid,
CircularProgress,
Divider,
} from '@material-ui/core';
import * as Yup from 'yup';
import { MyInput } from './comman/MyInput';
import axios from 'axios';
import { Event } from '../Tracking/Event';
import ThumbUpAltIcon from '@material-ui/icons/ThumbUpAlt';
import Unsubscribed from './Unsubscribed';
const contactSchema = Yup.object().shape({});
export default function SurveyUnsubscribed(props: any) {
const [isSubmitted, setIsSubmitted] = useState(false);
const [loading, setLoading] = useState(false);
const [count, setCount] = useState(0);
const [countone, setCountOne] = useState(0);
const [counttwo, setCountTwo] = useState(0);
const [countthree, setCountThree] = useState(0);
const [state, setState] = useState({
msg: '',
});
async function getInitialValues() {
try {
const response = await axios.get(
`${process.env.REACT_APP_LOCALHOST_DEVELOPMENT_VOTING_API_GET}`,
);
var voteone = response.data.map(function (obj: any) {
console.log('value',parseInt(obj.voteone))
return parseInt(obj.voteone);
});
var votetwo = response.data.map(function (obj: any) {
return obj.votetwo;
});
var votethree = response.data.map(function (obj: any) {
return obj.votethree;
});
var votefour = response.data.map(function (obj: any) {
return obj.votefour;
});
return {
voteone,
votetwo,
votethree,
votefour,
helptext: '',
};
} catch (error) {
console.error(error);
}
}
useEffect(() => {
getInitialValues().then((res: any) => setCount(res.voteone));
getInitialValues().then((res: any) => setCountOne(res.votetwo));
getInitialValues().then((res: any) => setCountTwo(res.votethree));
getInitialValues().then((res: any) => setCountThree(res.votefour));
}, []);
return (
<React.Fragment>
<Formik
enableReinitialize
initialValues={{
count: count,
countone: countone,
counttwo: counttwo,
countthree: countthree,
helptext: '',
}}
validationSchema={contactSchema}
onSubmit={(values, { resetForm }) => {
setLoading(true);
const data = {
count: values.count,
countone: values.countone,
counttwo: values.counttwo,
countthree: values.countthree,
helptext: values.helptext,
};
const request = new Request(
`${process.env.REACT_APP_LOCALHOST_DEVELOPMENT_VOTING_API}`,
{
method: 'POST',
headers: new Headers({
'Content-Type': 'application/json',
}),
body: JSON.stringify(data),
},
);
fetch(request)
.then((res) => res.json())
.then((data) => {
if (data.message === 'Thank you for your feedback!') {
setState({
msg: data.message,
});
setIsSubmitted(true);
setTimeout(() => {
setLoading(false);
}, 1500);
} else {
console.log('error');
}
});
setTimeout(() => {
setIsSubmitted(false);
}, 1500);
resetForm();
}}
>
{({ setFieldValue }) => (
<Grid container>
<Grid
item
xs={12}
style={{ paddingLeft: '2em', paddingRight: '2em' }}
>
{isSubmitted}
<Form>
<Typography
variant="body1"
style={{
display: 'flex',
alignItems: 'center',
marginBottom: '1em',
}}
>
<Field
type="hidden"
name="count"
component={ThumbUpAltIcon}
onClick={() => setCount( count + 1 )}
style={{ color: '#C4C4C4', marginRight: '0.4em' }}
/>
<Typography
variant="caption"
style={{
position: 'relative',
top: '1.5em',
right: '1.5em',
}}
>
{count}
</Typography>
Complaince and Tax Return Filing Dates.
</Typography>
<Typography
variant="body1"
style={{
display: 'flex',
alignItems: 'center',
marginBottom: '1em',
}}
>
<Field
type="hidden"
name="countone"
component={ThumbUpAltIcon}
onClick={() => setCountOne( countone + 1 )}
style={{ color: '#C4C4C4', marginRight: '0.4em' }}
/>
<Typography
variant="caption"
style={{
position: 'relative',
top: '1.5em',
right: '1.5em',
}}
>
{countone}
</Typography>
Excel Sheet for Calculation of GSTR 3B.
</Typography>
<Typography
variant="body1"
style={{
display: 'flex',
alignItems: 'center',
marginBottom: '1em',
}}
>
<Field
type="hidden"
name="counttwo"
component={ThumbUpAltIcon}
onClick={() => setCountTwo( counttwo + 1 )}
style={{ color: '#C4C4C4', marginRight: '0.4em' }}
/>
<Typography
variant="caption"
style={{
position: 'relative',
top: '1.5em',
right: '1.5em',
}}
>
{counttwo}
</Typography>
Excel Sheet for GSTR 2A vs ITC Books matching.
</Typography>
<Typography
variant="body1"
style={{
display: 'flex',
alignItems: 'center',
marginBottom: '1em',
}}
>
<Field
type="hidden"
name="countthree"
component={ThumbUpAltIcon}
onClick={() => setCountThree(countthree + 1)}
style={{ color: '#C4C4C4', marginRight: '0.4em' }}
/>
<Typography
variant="caption"
style={{
position: 'relative',
top: '1.5em',
right: '1.5em',
}}
>
{countthree}
</Typography>
Details of applicable law on directors and requirement of
Director KYC.
</Typography>
<br />
<Typography
variant="h6"
style={{
marginLeft: '2em',
marginTop: '0.5em',
}}
>
What information would help you ?
</Typography>
<Field
id="outlined-multiline-flexible"
type="text"
name="helptext"
component={MyInput}
disabled={isSubmitted}
style={{ marginLeft: '2em' }}
/>
<br />
<br />
<Button
type="submit"
variant="contained"
style={{
background: '#2F4858',
color: 'white',
fontFamily: 'roboto',
fontSize: '1rem',
marginLeft: '2em',
marginBottom: '1em',
}}
>
{loading && (
<CircularProgress
size={25}
color="inherit"
style={{ marginRight: '5px' }}
/>
)}
{loading && <span>submitting</span>}
{!loading && <span>Submit</span>}
</Button>
<br />
{state.msg && (
<Typography
variant="h6"
style={{
color: '#4BB543',
fontFamily: 'roboto-medium',
marginTop: '1em',
}}
>
{' '}
{state.msg}{' '}
</Typography>
)}
</Form>
<Divider
style={{
border: '1px solid #97A1A8',
marginTop: '1em',
marginBottom: '2em',
}}
/>
</Grid>
</Grid>
)}
</Formik>
</React.Fragment>
);
}
Whenever I have clicked on the thumbs-up icon value is incremented by one but value 1 is inserted in front of the previous one. I want to increment value by one. ( 1 increment by 2 ).

Thanks In advance guys.

Answer

It’s the nature of javascript when you add a string to a number

console.log(1+"1") // <-- Gives "11"
console.log(1+1)  // <-- Gives "2"

Your first count is fine, but when you get a response from the API, your res.voteone is definitely a string.

So you will need to parse your response to a number first:

useEffect(() => {
getInitialValues().then((res: any) => setCount(Number(res.voteone)));
getInitialValues().then((res: any) => setCountOne(Number(res.votetwo)));
getInitialValues().then((res: any) => setCountTwo(Number(res.votethree)));
getInitialValues().then((res: any) => setCountThree(Number(es.votefour)));
}, []);

OR

useEffect(() => {
getInitialValues().then((res: any) => setCount(parseInt(res.voteone)));
getInitialValues().then((res: any) => setCountOne(parseInt(res.votetwo)));
getInitialValues().then((res: any) => setCountTwo(parseInt(res.votethree)));
getInitialValues().then((res: any) => setCountThree(parseInt(es.votefour)));
}, []);

Number() and parseInt() behaves a bit different but in your case it’s not.