Apologies if this is a dumb question, but I am just learning React and useState. I have the below code that acts as a signup function. When a username and password are POST
to the API
, a message returns along with a token.
import { useState } from "react";
const API_URL = '';
export default function SignUpForm() {
const [username, setUsername] = useState("");
const [password, setPassword] = useState("");
const [error, setError] = useState(null);
async function handleSubmit(event) {
event.preventDefault();
try {
const response = await fetch(API_URL, {
method: "POST",
body: JSON.stringify({
username:username,
password:password,
}),
headers: {
'Content-type': 'application/json; charset=UTF-8'
}
})
const result = await response.json();
console.log(result);
//Attempting to use state function to grab token and store it.
setToken(result.token);
console.log(token)
} catch (error) {
setError(error.message)
}
}
return (
<>
<h2>Sign Up!</h2>
{error && <p>{error}</p>}
<form onSubmit={handleSubmit}>
<label>
Username: <input value={username} onChange={(e) => setUsername(e.target.value)}/>
</label>
<label>
Password: <input value={password} onChange={(e) => setPassword(e.target.value)}/>
</label>
<button>Submit</button>
</form>
</>
);
}
I am trying to use the useState
from the App.jsx
file below:
const [token, setToken] = useState(null);
to set the token.
import './App.css'
import SignUpForm from './components/SignUpForm'
import Authenticate from './components/Authenticate'
import { useState } from 'react';
function App() {
const [token, setToken] = useState(null);
return (
<>
<SignUpForm token={token} setToken={setToken} />
<Authenticate token={token} setToken={setToken} />
</>
);
}
export default App
I have been told to "deconstruct the setToken
function from props
." But I have no clue what this means. I’m not sure if I need to create another useState
of the same type inside the current file or not. How am I supposed to deconstruct setToken
? Can someone please help me out with this or point me in the right direction? Any help is greatly appreciated!
Also if anyone asks, API_URL
does have a value, I just took it out for security reasons.
2
Answers
You need some changes in your SignUpForm component :
you need to learn more about props in react and reconstruction props in react . here is a link : https://www.geeksforgeeks.org/destructuring-of-props-in-reactjs/
this will work for you:
here you can see detailed explanation:
https://react.dev/learn/passing-props-to-a-component#step-2-read-props-inside-the-child-component