I am following Coding with kevins SQL, Node, Express, and React JS tutorial on youtube. https://www.youtube.com/watch?v=rK6oTTbVbcY
I am at the point in the tutorial where I am supposed to input data into the webpage textbox, and upon clicking submit the data will display on the bottom of the webpage
Whenever I try to enter the first and last name in the corresponding textbox, it doesn’t display at the bottom of the page
here is my code from my App.js:
import './App.css';
import React, {useState} from ‘react’;
function App() {
const [employee, setEmployee] = useState({EmployeeID: 0, Firstname: '', Lastname: '', Age: 0, Gender: ''});
const [returnedData, setReturnedData] = useState([]);
const setInput = (e) => {
const {name, value} = e.target;
console.log(value);
if (name === 'EmployeeID' || name === 'Age') {
setEmployee(prevState => ({...prevState,
[name]: parseInt(name)
}) );
return;
}
setEmployee(prevState => ({
...prevState,
[name]: value
}));
}
const fetchData = async () => {
console.log(employee);
const newData = await fetch('/api', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
body: JSON.stringify({
name: employee.Firstname
})
})
.then(res => res.json())
console.log(newData[0]);
}
return (
<div className="App">
<input
type="number"
name="EmployeeID"
placeholder="EmployeeID"
onChange={setInput}>
</input>
<input
name="Firstname"
placeholder="Firstname"
onChange={setInput}>
</input>
<input
name="Lastname"
placeholder="Lastname"
onChange={setInput}>
</input>
<input
type="number"
name="Age"
placeholder="Age"
onChange={setInput}>
</input>
<input
name="Gender"
placeholder="Gender"
onChange={setInput}>
</input>
<button onClick={()=> fetchData()}>Clicky</button>
<button onClick={()=> fetchData()}>Create</button>
<p>EmployeeID: {returnedData.EmployeeID}</p>
<p>Firstname: {returnedData.Firstname}</p>
<p>Lastname: {returnedData.Lastname}</p>
<p>Age: {returnedData.Age}</p>
<p>Gender: {returnedData.Gender}</p>
{returnedData}
{returnedData.name}
</div>
);
}
export default App;`enter code here`
>Solution :
On the bottom of the page you try to display the content of returnedData , whereas setReturnedData is never called inside the code. you are just calling setInput to change employee.
returnedData is still an empty array [].
I believe you want to call the setReturnedData inside fetchData to update based on your API Call. Do this and it will probably display the data 🙂
Little hint for StackOverflow: instead of sharing screenshots, consider using CodeSandbox for creating an editable Project with your code, which might be easier to read and provide a solution for you.