react native multistep wizard formik yup - react-native

Hi I am new to react native.
I have react native project in which I have implement multistep form wizard with formik yup validation. Currently I have implemented multistep form wizard with formik yup validation in react.
How can I implement or convert it to react native.
Below is the code which implement in react.
import React, { useState } from 'react';
import { ErrorMessage, Field, Form, Formik } from "formik";
import * as Yup from "yup";
const Wizard = ({ children, initialValues, onSubmit }) => {
const [stepNumber, setStepNumber] = useState(0);
const steps = React.Children.toArray(children);
const [snapshot, setSnapshot] = useState(initialValues);
const step = steps[stepNumber];
const totalSteps = steps.length;
const isLastStep = stepNumber === totalSteps - 1;
const next = values => {
setSnapshot(values);
setStepNumber(Math.min(stepNumber + 1, totalSteps - 1));
};
const previous = values => {
setSnapshot(values);
setStepNumber(Math.max(stepNumber - 1, 0));
};
const handleSubmit = async (values, formikBag) => {
if (isLastStep) {
return onSubmit(values, formikBag);
} else {
next(values);
}
};
return (
<Formik
initialValues={snapshot}
onSubmit={handleSubmit}
validationSchema={step.props.validationSchema}
>
{formik => (
<Form>
<p>
Step {stepNumber + 1} of {totalSteps}
</p>
{step}
<div style={{ display: "flex" }}>
{stepNumber > 0 && (
<button onClick={() => previous(formik.values)} type="button">
Back
</button>
)}
<div>
<button disabled={formik.isSubmitting} type="submit">
{isLastStep ? "Submit" : "Next"}
</button>
</div>
</div>
</Form>
)}
</Formik>
);
};
const WizardStep = ({ children }) => children;
const Demo = () => {
const submitform=(values)=>{
alert('First name:'+values.firstName+' Last name:'+values.lastName+' Mobile:'+values.mobile+' Email:'+values.email);
}
return(
<>
<Wizard
initialValues={{
email: "",
firstName: "",
lastName: "",
mobile:''
}}
onSubmit={values => submitform(values)}
>
<WizardStep
validationSchema={Yup.object({
firstName: Yup.string().required("required"),
lastName: Yup.string().required("required")
})}
>
<div>
<label htmlFor="firstName">First Name</label>
<Field
autoComplete="given-name"
component="input"
id="firstName"
name="firstName"
placeholder="First Name"
type="text"
/>
<ErrorMessage className="error" component="div" name="firstName" />
</div>
<div>
<label htmlFor="lastName">Last Name</label>
<Field
autoComplete="family-name"
component="input"
id="lastName"
name="lastName"
placeholder="Last Name"
type="text"
/>
<ErrorMessage className="error" component="div" name="lastName" />
</div>
</WizardStep>
<WizardStep
validationSchema={Yup.object({
mobile: Yup.number('Invalid mobile').min(10,"Invalid mobile").required("required")
})}
>
<div>
<label htmlFor="mobile">Mobile</label>
<Field
autoComplete="mobile"
component="input"
id="mobile"
name="mobile"
placeholder="Mobile"
type="text"
/>
<ErrorMessage className="error" component="div" name="mobile" />
</div>
</WizardStep>
<WizardStep
validationSchema={Yup.object({
email: Yup.string()
.email("Invalid email address")
.required("required")
})}
>
<div>
<label htmlFor="email">Email</label>
<Field
autoComplete="email"
component="input"
id="email"
name="email"
placeholder="Email"
type="text"
/>
<ErrorMessage className="error" component="div" name="email" />
</div>
</WizardStep>
</Wizard>
</>
)
}
function App() {
return (
<div className="App">
<Demo />
</div>
);
}
export default App;

Related

File upload using formik and express backend

I am trying to upload an image along with a title and some text for a post. I am using Formik form with an onSubmit in the client folder of the project :
const [charCount, setCharCount] = useState(0);
const [fileObject, setFileObject] = useState(null);
const initialValues = {
title: "",
postText: "",
file: null
};
const validationSchema = Yup.object({
title: Yup.string().required("Required"),
postText: Yup.string().required("Required"),
});
const onSubmitHandler = (values) => {
const formData = new FormData();
formData.append("title", values.title);
formData.append("postText", values.postText);
console.log(fileObject);
formData.append("file", document.getElementById("file").files[0]);
console.log(formData);
axios
.post(
"http://localhost:3001/posts/create",
formData,
{
headers: {
accessToken: localStorage.getItem("token"),
},
}
)
.then((response) => {
console.log(response.data);
});
};
return (
<>
<Formik
initialValues={initialValues}
validationSchema={validationSchema}
onSubmit={onSubmitHandler}
>
<Form className="create-post-form">
<input type="file" name="file" id="file" onChange={(e) => {
setFileObject(e.target.files[0]);
}}/>
<Field id="input-create-post" name="title" placeholder="Post Title" />
<ErrorMessage name="title" component="span" className="error" />
<Field
id="input-create-post-text"
name="postText"
placeholder="What's the story?"
as="textarea"
onKeyUp={(e) => setCharCount(e.target.value.length)}
maxLength="250"
/>
<div className="char-count">
<span id={charCount===250 ? "char-count-max" : "char-count"}>{charCount}/250</span>
</div>
<ErrorMessage name="title" component="span" className="error" />
<Button type="submit" title="Post" onSubmit={onSubmitHandler} />
</Form>
</Formik>
</>
);
};
On the server side (server folder), in the Posts.js route where I am handling the request :
router.post("/create",validateToken, async(req,res)=>{
if(req.files === null){
return res.status(400).json({message: "No file uploaded"});
}
const file = req.files;
console.log(file);
res.json(req.body)
})
On submitting the form, an empty object {} is logged on the console. And the res.json(req.body) returns the title and postText successfully, but the file is {} (empty). How do I fix this? Please help!
I tried submitting the form with the above code and got this response:
result image
I need the file object to be the actual fileObject that I have as a state.

How to toggle show hide functionality for multiple fields in formik?

import React, { Fragment, useState, useEffect } from "react";
import { useSelector, useDispatch, connect } from "react-redux";
import { useNavigate } from "react-router";
import { Field, Form, Formik } from "formik";
import VisibilityIcon from "#material-ui/icons/Visibility";
import VisibilityOffIcon from "#material-ui/icons/VisibilityOff";
import { changePassword } from "../../Redux/Actions/changePasswordAction";
import { passwordErrors, roles } from "../Shared/constants";
import Alert from "../Modal/modal";
import "./ChangePassword.css";
function ChangePassword() {
const [showPassword1, setShowPassword1] = useState(false);
const [showPassword2, setShowPassword2] = useState(false);
const [showPassword3, setShowPassword3] = useState(false);
const alert = useSelector((state) => state.alert);
enter code here
const role_id = localStorage.getItem("role_id");
//Redux Dispatch:
const dispatch = useDispatch();
//Used to navigate
const navigation = useNavigate();
const passwords = {
currentPassword: "",
newPassword: "",
confirmNewPassword: "",
};
// function toggleShowPassword(clickedField) {
// if (clickedField === showPassword1) {
// setShowPassword1(!showPassword1) &&
// setShowPassword2(showPassword2) &&
// setShowPassword3(showPassword3);
// } else if (clickedField === showPassword2) {
// setShowPassword2(!showPassword2) &&
// setShowPassword1(showPassword1) &&
// setShowPassword3(showPassword3);
// } else {
// setShowPassword3(!showPassword3) &&
// setShowPassword1(showPassword1) &&
// setShowPassword2(showPassword2);
// }
// }
function toggleShowPassword1() {
setShowPassword1(!showPassword1);
}
function toggleShowPassword2() {
setShowPassword2(!showPassword2);
}
function toggleShowPassword3() {
setShowPassword3(!showPassword3);
}
//Alert
useEffect(() => {
if (Number(role_id) === roles.TRAINER_ROLE_ID) {
if (alert.type === "success_clear") {
navigation("/trainer-profile");
}
} else {
if (alert.type === "success_clear") {
navigation("/user-profile");
}
}
}, [alert, navigation, role_id]);
function validate(passwords) {
const errors = {};
if (passwords.currentPassword === "") {
errors.currentPassword = passwordErrors.PASSWORD;
}
if (passwords.newPassword === passwords.currentPassword) {
errors.newPassword = passwordErrors.OLD_NEW_SAME;
}
if (passwords.newPassword === "") {
errors.newPassword = passwordErrors.PASSWORD;
} else if (
!/^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!##%&])(?=.{8,})/.test(
passwords.newPassword
)
) {
errors.newPassword = passwordErrors.PASSWORD_INVALID;
}
if (passwords.confirmNewPassword === "") {
errors.confirmNewPassword = passwordErrors.CONFIRM_PASSWORD;
} else if (passwords.confirmNewPassword !== passwords.newPassword) {
errors.confirmNewPassword = passwordErrors.PASSWORDS_UNMATCHED;
}
return errors;
}
function handleChangePassword(passwords) {
const id = localStorage.getItem("user_id");
const passwordsData = {
oldPassword: passwords.currentPassword,
password: passwords.confirmNewPassword,
};
dispatch(changePassword(id, passwordsData));
}
return (
<Fragment>
<div className="row">
<div className="col">
<span className="main-heading mx-4">Change Account Password</span>
<div className="mx-4">
<hr></hr>
</div>
</div>
</div>
{alert.message && <Alert show={true} />}
<div className="passwords">
<Formik
initialValues={passwords}
validate={(values) => validate(values)}
onSubmit={(values) => handleChangePassword(values)}
>
{({ errors, touched }) => (
<Form>
<div className="row">
<div className="col-md">
<div className="form-group mb-4">
<label htmlFor="currentPassword" className="cp-label">
Current Password
</label>
<div className="input-group">
<Field
type={showPassword1 ? "text" : "password"}
id="currentPassword"
name="currentPassword"
placeholder="Enter your Current password"
className={
errors.currentPassword && touched.currentPassword
? "form-control primary-input-field is-invalid pass"
: "form-control primary-input-field pass"
}
/>
<span
className="input-group-text"
id="basic-addon2"
// onClick={() => toggleShowPassword(showPassword1)}
onClick={toggleShowPassword1}
>
{showPassword1 ? (
<VisibilityIcon
fontSize="small"
className="iconColor"
/>
) : (
<VisibilityOffIcon
fontSize="small"
className="iconColor"
/>
)}
</span>
{touched.currentPassword && errors.currentPassword ? (
<div className="invalid-feedback">
{errors.currentPassword}
</div>
) : null}
</div>
</div>
</div>
</div>
<div className="row">
<div className="col-md">
<div className="form-group mb-4">
<label htmlFor="newPassword" className="cp-label">
New Password
</label>
<div className="input-group">
<Field
type={showPassword2 ? "text" : "password"}
id="newPassword"
name="newPassword"
placeholder="Enter your New password"
className={
errors.newPassword && touched.newPassword
? "form-control primary-input-field is-invalid pass"
: "form-control primary-input-field pass"
}
/>
<span
className="input-group-text"
id="basic-addon2"
// onClick={() => toggleShowPassword(showPassword2)}
onClick={toggleShowPassword2}
>
{showPassword2 ? (
<VisibilityIcon
fontSize="small"
className="iconColor"
/>
) : (
<VisibilityOffIcon
fontSize="small"
className="iconColor"
/>
)}
</span>
{touched.newPassword && errors.newPassword ? (
<div className="invalid-feedback">
{errors.newPassword}
</div>
) : null}
</div>
</div>
</div>
</div>
<div className="row">
<div className="col-md">
<div className="form-group mb-4">
<label htmlFor="confirmNewPassword" className="cp-label">
Confirm New Password
</label>
<div className="input-group">
<Field
type={showPassword3 ? "text" : "password"}
id="confirmNewPassword"
name="confirmNewPassword"
placeholder="Confirm your New password"
className={
errors.confirmNewPassword &&
touched.confirmNewPassword
? "form-control primary-input-field is-invalid pass"
: "form-control primary-input-field pass"
}
/>
<span
className="input-group-text"
id="basic-addon2"
// onClick={() => toggleShowPassword(showPassword3)}
onClick={toggleShowPassword3}
>
{showPassword3 ? (
<VisibilityIcon
fontSize="small"
className="iconColor"
/>
) : (
<VisibilityOffIcon
fontSize="small"
className="iconColor"
/>
)}
</span>
{touched.confirmNewPassword &&
errors.confirmNewPassword ? (
<div className="invalid-feedback">
{errors.confirmNewPassword}
</div>
) : null}
</div>
</div>
</div>
</div>
<div className="row mt-4">
<div className="col text-end">
<button className="btn primary-button" type="submit">
Change Password
</button>
</div>
</div>
</Form>
)}
</Formik>
</div>
</Fragment>
);
}
const mapStateToProps = (state) => ({
changePassword: state.changePassword,
});
export default connect(mapStateToProps, {
changePassword,
})(ChangePassword);
Please someone help me to apply only one function that can toggle show and hide for three fields, I have already tried one function but it's not working. I couldn't know what to do ? I need one function there to toggle eye symbol when it is clicked, but with the function I have used it's changing and I am pressing for one field and another field's being shown, please someone explain me

ID is not passed to edit page, getting 404 because URL shows undefined for ID in console but is right in URL

The above I hope help showing the Home.js pulling the User info working properly. When I click the Edit button for either User it takes me to the edit page where the URL shows properly pulling it for ID 5. The issue is that the page loads the form properly accept it has no user data prefilled based on the ID. I get the error below the URL about the ID being undefined. This is being pulled from an SQL database and the data is being pulled from a SPROC provided below which runs the Home Page fine but for some reason is not able to get the ID to do the edit page.
Any help please to get this resolved.
Home.js
(this pulls the data fine with the same get sproc as the edit)
import axios from "axios";
import { Link } from "react-router-dom";
const Home = () => {
const [users, setUser] = useState([]);
useEffect(() => {
loadUsers();
}, []);
const loadUsers = async () => {
const result = await axios.get(`http://localhost:5000/getCollectors`);
setUser(result.data.reverse());
};
const deleteUser = async CollectorID => {
await axios.delete(`http://localhost:5000/deleteCollector/${CollectorID}`);
loadUsers();
};
return (
<div className="container">
<div className="py-4">
<h1>Home Page</h1>
<table className="table border shadow">
<thead className="thead-dark">
<tr>
<th scope="col">ID</th>
<th scope="col">Active</th>
<th scope="col">Name | Code</th>
<th scope="col">Aging Bucket</th>
<th scope="col">Program Bucket</th>
<th scope="col">Finance Company</th>
<th>Action</th>
</tr>
</thead>
<tbody>
{users.map((user) => (
<tr key={user.CollectorID}>
{/* <th scope="row">{index + 1}</th> */}
<th scope="row">{user.CollectorID}</th>
<td></td>
<td>{user.FirstName} {user.LastName} | {user.CollectorCode}</td>
<td></td>
<td></td>
<td>{user.FinanceCompany}</td>
<td>
<Link className="btn btn-primary mr-2" to={`/users/${user.CollectorID}`}>
View
</Link>
<Link
className="btn btn-outline-primary mr-2"
to={`/users/edit/${user.CollectorID}`}
>
Edit
</Link>
<Link
className="btn btn-danger"
onClick={() => deleteUser(user.CollectorID)}
>
Delete
</Link>
</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
);
};
export default Home;
EditUser.js
(uses same sproc as the Home.js but trying to get by user ID which is where it breaks)
import axios from "axios";
import { useHistory, useParams } from "react-router-dom";
const EditUser = () => {
let history = useHistory();
const { CollectorID } = useParams();
const [user, setUser] = useState({
// CollectorID: '',
// ProgramBucketID: '',
// CollectorOptionsID: '',
// FinanceCompanyID: '',
Active: '',
LastName: '',
CollectorCode: '',
Aging1to15: '',
Aging31to45: '',
Aging31to60: '',
AgingOver60: '',
ProgramBucketA: '',
ProgramBucketB: '',
ProgramBucketC: '',
ProgramBucketSU: '',
FinanceCompany: ''
});
const { Active, LastName, CollectorCode, Aging1to15, Aging31to45, Aging31to60, AgingOver60, ProgramBucketA, ProgramBucketB, ProgramBucketC, ProgramBucketSU, FinanceCompany} = user;
const onInputChange = e => {
setUser({ ...user, [e.target.name]: e.target.value });
};
useEffect(() => {
loadUser();
}, []);
const onSubmit = async e => {
e.preventDefault();
await axios.put(`http://localhost:5000/UpdateUser/${CollectorID}`, user);
history.push("/");
};
const loadUser = async () => {
const result = await axios.get(`http://localhost:5000/getCollectors/${CollectorID}`);
setUser(result.data);
console.log(result.data);
};
return (
<div className="container">
<div className="w-75 mx-auto shadow p-5">
<h2 className="text-center mb-4">Edit A User</h2>
<form onSubmit={e => onSubmit(e)}>
<div className="form-group">
<input
type="text"
className="form-control form-control-lg"
placeholder="Active Status"
name="Active"
value={Active}
onChange={e => onInputChange(e)}
/>
</div>
<div className="form-group">
<input
type="text"
className="form-control form-control-lg"
placeholder="Enter Your Last Name"
name="LastName"
value={LastName}
onChange={e => onInputChange(e)}
/>
</div>
<div className="form-group">
<input
type="text"
className="form-control form-control-lg"
placeholder="Enter Your Collector Code"
name="CollectorCode"
value={CollectorCode}
onChange={e => onInputChange(e)}
/>
</div>
<div className="form-group">
<input
type="text"
className="form-control form-control-lg"
placeholder="Aging1to15"
name="Aging1to15"
value={Aging1to15}
onChange={e => onInputChange(e)}
/>
</div>
<div className="form-group">
<input
type="text"
className="form-control form-control-lg"
placeholder="Aging31to45"
name="Aging31to45"
value={Aging31to45}
onChange={e => onInputChange(e)}
/>
</div>
<div className="form-group">
<input
type="text"
className="form-control form-control-lg"
placeholder="Aging31to60"
name="Aging31to60"
value={Aging31to60}
onChange={e => onInputChange(e)}
/>
</div>
<div className="form-group">
<input
type="text"
className="form-control form-control-lg"
placeholder="AgingOver60"
name="AgingOver60"
value={AgingOver60}
onChange={e => onInputChange(e)}
/>
</div>
<div className="form-group">
<input
type="text"
className="form-control form-control-lg"
placeholder="ProgramBucketA"
name="ProgramBucketA"
value={ProgramBucketA}
onChange={e => onInputChange(e)}
/>
</div>
<div className="form-group">
<input
type="text"
className="form-control form-control-lg"
placeholder="ProgramBucketB"
name="ProgramBucketB"
value={ProgramBucketB}
onChange={e => onInputChange(e)}
/>
</div>
<div className="form-group">
<input
type="text"
className="form-control form-control-lg"
placeholder="ProgramBucketC"
name="ProgramBucketC"
value={ProgramBucketC}
onChange={e => onInputChange(e)}
/>
</div>
<div className="form-group">
<input
type="text"
className="form-control form-control-lg"
placeholder="ProgramBucketSU"
name="ProgramBucketSU"
value={ProgramBucketSU}
onChange={e => onInputChange(e)}
/>
</div>
<div className="form-group">
<input
type="text"
className="form-control form-control-lg"
placeholder="FinanceCompany"
name="FinanceCompany"
value={FinanceCompany}
onChange={e => onInputChange(e)}
/>
</div>
<button className="btn btn-warning btn-block">Update User</button>
</form>
</div>
</div>
);
};
export default EditUser;
Server.js
const cors = require('cors');
const bodyParser = require('body-parser');
const config = require('./src/dbfiles/dbConfig')
const app = express();
app.use(cors());
app.use(bodyParser.json({ extended: true }));
var sql = require("mssql");
// Get collectors
app.get('/getCollectors', (req, res) => {
sql.connect(config).then(pool => {
return pool.request()
.query(`Exec [CollectorAssignment].[sCollectorGet]`).then(result => {
res.send(result.recordset)
})
})
})
// Add Collector Personal Info
app.post('/addCollector', function (req, res) {
sql.connect(config).then(pool => {
return pool.request()
.query(`Exec CollectorAssignment.sCreateCollector
#Active='${req.body.Active}',
#FirstName='${req.body.FirstName}',
#MiddleInitial='${req.body.MiddleInitial}',
#LastName='${req.body.LastName}',
#CollectorCode='${req.body.CollectorCode}',
#CollectionTeamID='${req.body.CollectionTeamID}',
#Aging1to15='${req.body.Aging1to15}',
#Aging31to45='${req.body.Aging31to45}',
#Aging31to60='${req.body.Aging31to60}',
#AgingOver60='${req.body.AgingOver60}',
#ProgramBucketA='${req.body.ProgramBucketA}',
#ProgramBucketB='${req.body.ProgramBucketB}',
#ProgramBucketC='${req.body.ProgramBucketC}',
#ProgramBucketSU='${req.body.ProgramBucketSU}',
#FinanceCompany='${req.body.FinanceCompany}'
`)
.then(result => {
res.send(result)
})
})
});
//Update Collector
app.put('/UpdateUser/:CollectorID', function (req, res) {
sql.connect(config).then(pool => {
return pool.request()
.query(`Exec CollectorAssignment.sUpdateCollector
#CollectorID='${req.body.CollectorID}',
#CollectorOptionsID='${req.body.CollectorOptionsID}',
#ProgramBucketID='${req.body.ProgramBucketID}',
#FinanceCompanyID='${req.body.FinanceCompanyID}',
#Active='${req.body.Active}',
#LastName='${req.body.LastName}',
#CollectorCode='${req.body.CollectorCode}',
#Aging1to15='${req.body.Aging1to15}',
#Aging31to45='${req.body.Aging31to45}',
#Aging31to60='${req.body.Aging31to60}',
#AgingOver60='${req.body.AgingOver60}',
#ProgramBucketA='${req.body.ProgramBucketA}',
#ProgramBucketB='${req.body.ProgramBucketB}',
#ProgramBucketC='${req.body.ProgramBucketC}',
#ProgramBucketSU='${req.body.ProgramBucketSU}',
#FinanceCompany='${req.body.FinanceCompany}'
`)
.then(result => {
res.send(result.recordset)
})
})
});
// Delete Collector
app.delete('/deleteCollector/:CollectorID', (req, res) => {
sql.connect(config).then(pool => {
return pool.request()
.query(`DELETE FROM CollectorAssignment.tCollectorsTest
WHERE CollectorID = ${req.params.CollectorID}`).then(result => {
res.send(result.recordset)
})
})
})
app.listen(5000, () => {
console.log('running on port 5000');
})
Stored Procedure being ran for the getCollectors
GO
/****** Object: StoredProcedure [CollectorAssignment].[sCollectorGet] Script Date: 3/29/2022 2:37:07 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: Wesley Seitz
-- Create date: 01/13/2022
-- Description: To pull in collector information for the options page of the assignmnet tool
-- =============================================
ALTER PROCEDURE [CollectorAssignment].[sCollectorGet]
-- Add the parameters for the stored procedure here
--#CollectorID INT
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
SELECT
Active,
FirstName,
LastName,
CollectorCode,
Aging1to15,
Aging31to45,
Aging31to60,
AgingOver60,
ProgramBucketA,
ProgramBucketB,
ProgramBucketC,
ProgramBucketSU,
FinanceCompany,
tCollectorsTest.CollectorID,
tCollectorOptionsTest.ProgramBucketID,
tCollectorOptionsTest.FinanceCompanyID,
tCollectorOptionsTest.CollectorOptionsID
FROM CollectorAssignment.tCollectorsTest
INNER JOIN CollectorAssignment.tCollectorOptionsTest ON tCollectorOptionsTest.CollectorID = tCollectorsTest.CollectorID
INNER JOIN CollectorAssignment.tProgramBucketTest ON tProgramBucketTest.ProgramBucketID = tCollectorOptionsTest.ProgramBucketID
INNER JOIN CollectorAssignment.tFinanceCompanyTest ON tFinanceCompanyTest.FinanceCompanyID = tCollectorOptionsTest.FinanceCompanyID
END
As discussed in the comments, your issue here was that, in your EditUser component, you were trying to access a property called CollectorID from the result of useParams() but the only property in this object was id. Changing the line
const { CollectionID } = useParams();
to
const { id } = useParams();
and then changing subsequent references from CollectorID to id resolves the 404 by populating the correct id in the url.
Your follow-up question of why you are not seeing your data populate in the EditUser component should probably be asked in another question (I'd advise trying to recreate the issue with a simpler code example).

Having problems calling an API id

Hi I am having some problems figuring out how to access an id. I am making a twitter cloner and I have an Icon I would like to click and see what people are commenting on it. But I have hit a wall and cant figure out how to access the Id when the chatbubble is clicked.
Any help would be greatly appreciated. The API works perfectly and I can call an id through postman.
const GetData = (id) => {
axios.get('https://localhost:44368/api/users/{id}').then((response) => {
console.log(response.data, "list of heroes ");
});
};
return (
<div className="post">
<div className="ppictur">
<Avatar src={avatar} />
</div>
<div className="post_body">
<div className="post_header">
<div className="post_headerText">
<h3>
{displayName}
<span className="post_headerSpecial">
<VerifiedIcon className="post_badge" />
#{username}
</span>
</h3>
</div>
<div className="post_headerDesription">
<p>{text}</p>
</div>
</div>
<img src={image} alt="" />
<div className="post_footer">
<ChatBubbleOutlineIcon onClick={GetData()} />
<RepeatIcon fontSize="small" />
<FavoriteBorderIcon fontSize="small" />
<PublishOutlinedIcon fontSize="small" />
</div>
</div>
</div>
);
}
export default Post;
const [posts, setPosts] = useState([]);
useEffect(() => {
axios.get('https://localhost:44368/api/users').then((response) => {
console.log(response.data, "list of heroes ");
setPosts(response.data);
});
}, []);
const icon = document.getElementById("Dark");
function DarkM() {
document.body.classList.toggle("dark-theme");
}
return (
<div className="commentbox">
<div className="header">
<h2>Home</h2>
<DarkModeOutlinedIcon id="Dark" onClick={() => DarkM(icon)} />
</div>
<Opinion />
{posts.map(post => (
<Post
avatar={post.profilePicture}
displayName={post.name}
username={post.userName}
text={post.post}
image={post.image}
bull
/>
)).reverse()}
</div>
);
}
export default Feed; ```
Use template literal ES6 with backticks.
const GetData = (id) => {
axios.get(`https://localhost:44368/api/users/${id}`).then((response) => {
console.log(response.data, "list of heroes ");
});
};
Also when you call it, make sure to pass arguments.
<ChatBubbleOutlineIcon onClick={GetData(9)} />
In my other component i wasnt pushing all the data through. that is my props didnt know what i was trying to call
const objectToPass = {
postId, avatar, displayName, username, text, image
}
const showSingleData = (value) => {
navigate(`/tweet/${value.postId}`)
console.log(value)
}```
it was a problem with my other component

Resetting a formik form in react-native on navigation

I am trying to create a React Native app that can create and edit entities.
For example, users.
I have a formik form that takes first and last name, as well as an email address.
If a user params is passed, then the form should take on those values.
However, it only works the first time. After that, the form keeps the first values.
How can I force the form to be reevaluated?
function FormScreen({ navigation, route }) {
const formikRef = React.createRef();
const initialValues = { firstName: "", lastName: "", email: "" };
if (route.params && route.params.user) {
if (route.params.user.firstName) {
initialValues.firstName = route.params.user.firstName;
}
if (route.params.user.lastName) {
initialValues.lastName = route.params.user.lastName;
}
if (route.params.user.email) {
initialValues.email = route.params.user.email;
}
}
const unsubscribeBlur = navigation.addListener("blur", (e) => {
console.log("form blur");
if (formikRef.current) {
console.log("form reset");
formikRef.current?.resetForm();
}
});
return (
<View style={{ flex: 1, alignItems: "center", justifyContent: "center" }}>
<Formik
innerRef={formikRef}
initialValues={initialValues}
validationSchema={Yup.object({
firstName: Yup.string()
.max(15, "Must be 15 characters or less")
.required("Required"),
lastName: Yup.string()
.max(20, "Must be 20 characters or less")
.required("Required"),
email: Yup.string()
.email("Invalid email address")
.required("Required"),
})}
onSubmit={(values, { setSubmitting }) => {
setTimeout(() => {
alert(JSON.stringify(values, null, 2));
setSubmitting(false);
}, 400);
}}
>
<Form>
<label htmlFor="firstName">First Name</label>
<Field name="firstName" type="text" />
<ErrorMessage name="firstName" />
<label htmlFor="lastName">Last Name</label>
<Field name="lastName" type="text" />
<ErrorMessage name="lastName" />
<label htmlFor="email">Email Address</label>
<Field name="email" type="email" />
<ErrorMessage name="email" />
<button type="submit">Submit</button>
</Form>
</Formik>
</View>
);
}
export default FormScreen;
I have code in there to reset the form on blur but the reset doesn't seem to do anything.
You can find the complete code in a snack.
https://snack.expo.io/#hackzilla/create-and-edit-with-formik
Because you are using a tab navigator. The home and form screen will not reMount when you toggle between them.So the formik will not load the new initialValues.In your way,you can reset the form using route params everytime the form screen is focused.But a better way is using a stack navigator,every time create a form using a new instance.
useFocusEffect(
React.useCallback(() => {
if (formikRef.current) {
console.log("form reset");
formikRef.current?.setValues(initialValues);
}
})
);
We can reset the form after submit, so that it will clear all the fields. Please try by replacing your submit method with below mentioned code.
onSubmit={(values, { setSubmitting, resetForm }) => {
setTimeout(() => {
alert(JSON.stringify(values, null, 2));
setSubmitting(false);
// reset the fields after submit
resetForm();
}, 400);
}}