Reputation: 786
Well this is my Axios POST request:
import React, {useState} from "react";
import Axios from "axios";
const [data, setData] = useState({
number: "",
password: "",
code: ""
})
function handle(e) {
const newdata = { ...data };
newdata[e.target.id] = e.target.value;
setData(newdata);
// console.log(newdata);
}
function submit(e) {
e.preventDefault();
const url = 'EXAMPLE';
Axios.post(url, {
number: data.number,
password: data.password,
code: data.code
}).then((response) => {
if (response.ok) {
return response.json();
}
throw new Error('Something went wrong.');
})
.then((responseJson) => {
// console.log(responseJson.number);
console.log(responseJson);
}).catch((error) => {
console.log(error + ", Or Please check your internet connection and try again.");
})
}
Which is working fine and I recieve respond from server, But when I convert it to the Fetch like This:
import React, {useState} from "react";
const [data, setData] = useState({
number: "",
password: "",
code: ""
})
function handle(e) {
const newdata = { ...data };
newdata[e.target.id] = e.target.value;
setData(newdata);
// console.log(newdata);
}
function submit(e) {
e.preventDefault();
const url = 'EXAMPLE';
fetch(url, {
method: 'POST',
body: JSON.stringify(data)
}).then((response) => {
if (response.ok) {
return response.json();
}
throw new Error('Something went wrong.');
})
.then((responseJson) => {
// console.log(responseJson.number);
console.log(responseJson);
}).catch((error) => {
console.log(error + ", Or Please check your internet connection and try again.");
})
}
it doesn't work and when I use Network => Payload tab Request is working just like Axios, But no respond is detected. Why is that happening? maybe I'm missing something? My convert is wrong in body?
Upvotes: 0
Views: 595
Reputation: 54984
In general:
function Foo(){
let [data, setData] = useState()
useEffect(() => {
fetch(`some url that has json output`).then(r => r.json()).then(setData)
}, [])
return <pre>{JSON.stringify(data, null, 2)}</pre>
}
Upvotes: 1