The account number is part of userData and I’m displaing userData in another component. It is genrating the account number perfectly but not the first time because it is set to null.
I tried to use useEffect but then it is just generating the same number for every create
function CreateAccount() {
// Define state variables to manage user input``
const [fullName, setFullName] = useState("");
const [balance, setBalance] = useState(null);
const [gender, setGender] = useState("");
const [address, setAddress] = useState("");
const [accountNumber, setAccountNumber] = useState(null);
// Get the setUserData function from the RegisterContext
const { setUserData } = useContext(RegisterContext);
// Function to handle form submission
const handleSubmit = (event) => {
event.preventDefault();
// Generate account number
const generatedAccountNumber = Math.floor(Math.random() * 1000000000);
// Gather user input data including the generated account number
const userData = {
fullName,
balance,
gender,
address,
accountNumber
};
// Update the userData state in the context provider
setUserData(userData);
// Set the accountNumber state once
setAccountNumber(generatedAccountNumber);
>Solution :
Your problem will be resolved if you call your Math.floor(Math.random() * 1000000000) in the useState hook const [accountNumber, setAccountNumber] = useState(null);
This will init the state with a random "account number" every time.
I modified your code a bit to init the accountNumber state on mount
// suggestion to move this function yo maybe utils.js or something
function generateAccountId() {
return Math.floor(Math.random() * 1000000000);
};
function CreateAccount() {
// Define state variables to manage user input``
const [fullName, setFullName] = useState("");
const [balance, setBalance] = useState(null);
const [gender, setGender] = useState("");
const [address, setAddress] = useState("");
// When the component is mounted we generate an account ID
const [accountNumber, setAccountNumber] = useState(generateAccountId);
// Get the setUserData function from the RegisterContext
const { setUserData } = useContext(RegisterContext);
// Function to handle form submission
const handleSubmit = (event) => {
event.preventDefault();
// Gather user input data including the generated account number
const userData = {
fullName,
balance,
gender,
address,
accountNumber
};
// Update the userData state in the context provider
setUserData(userData);
}
After this modification, every time your component mounts the accountNumber will be generated for you in the useState hook. You can init useState with a function which is the approach I used.
No state solution
Another improvement would be not to even use state at all, just do this
// Gather user input data and generate an account id
const userData = {
fullName,
balance,
gender,
address,
accountNumber:generateAccountId()
};
This will always generate a new accountNumber when the userDetails object is created