I want to print userData in my db.jason in the console.log() when the button is pressed in the Data component but I am not able to print. I am getting errors in my <App.tsx> components.
//Error
//App.tsx
ERROR in src/App.tsx:31:8
TS2786: 'Data' cannot be used as a JSX component.
Its return type 'void' is not a valid JSX element.
29 | return (
30 | <div className="App">
> 31 | <Data />
| ^^^^
32 | </div>
33 | );
34 | }
I don't know what I have done wrong. I request you to point out the mistake I have made to do this to me.
//App.js
import Data from "./Components/http";
function App() {
const [user, setUser] = useState(true);
return (
<div className="App">
<Data />
</div>
);
}
export default App;
//db.jason
{
"userData": [
{
"id": 1,
"name": "Gibson",
"age": "21"
},
{
"id": 2,
"name": "Joseph",
"age": "12"
}
]
}
import axios from "axios";
export function getUser() {
return axios
.get("http://localhost:3006/userData")
.then((res) => {
console.log(res.data);
})
.catch((err) => console.log(err));
}
//Data.tsx
import { getUser } from "../Api/api";
export default function Data() {
function displayuser() {
getUser();
return (
<div>
<button onClick={displayuser}>get</button>
</div>
);
}
}
CodePudding user response:
I think you have a problem in parentheses. Try this:
export default function Data() {
function displayuser() {
getUser()
}
return (
<div>
<button onClick={displayuser}>get</button>
</div>
)
}
CodePudding user response:
Your error is "data cannot be used as a jsx element". You are trying to use a component in your jsx (after your return). So instead of doing something like this:
return (
<div className="app">
<data />
</div>
)
You should put it inside curly brackets like this:
return (
<div className="app">
{<data />}
</div>
)
Whenever you are using some function, variable or whatever that is not plain jsx, you need to put it inside curly brackets.