I have implemented a external API function to return text/html when a button is clicked. But is doesn't seem return the data. instead a promise is returned.
<TouchableOpacity onPress={() => getData() }>
<Text style={styles.button}>Register</Text>
</TouchableOpacity>
the fetch function
const getData= () => {
let formData = new FormData();
formData.append("name", 'ABC');
formData.append("age", 35)
fetch(API_URL, {
method: 'POST',
body: formData,
}).then(response => {
console.log('success');
console.log(JSON.stringify(response.text()))
}).catch(error => {
console.log('error');
console.error(JSON.stringify(response));
})
}
I want only the html/text response
You'll need to handle the response.JSON first:
const getData= () => {
let formData = new FormData();
formData.append("name", 'ABC')
formData.append("age", 35)
fetch(API_URL, {
method: 'POST',
body: formData,
})
.then(response => response.json())
.then(response => {
console.log(response)
})
.catch(error => {
console.log('error')
})
}
Check out this documentation for more details.
Related
I don’t understand how to upload a photo correctly and then upload it to the page.
I'm a beginner, can you please tell me what I did wrong?
const [photo, setPhoto] = useState('');
const handleSubmit = (e) => {
e.preventDefault();
const users = {name, email, phone, position, photo}
setIsPending(true);
fetch("http://localhost:8000/users", {
method: 'POST',
headers: {'Content-Type':'application/json'},
body: JSON.stringify(users)
}).then(() => {
console.log('well');
setIsPending(false);
})
}
<form className="form" onSubmit={handleSubmit}>
<UploadFile
name="file"
onChange={(e) => setPhoto(e.target.files[0])}
value= {photo}
/>
<Button type="submit"/>
</form>
First of all you have to find a service that allows you to upload a file.
for example: https://api.imgur.com/endpoints/image/
there instructions inside.
However if you want to use fetch method I will give you an example how it should look like.
const handleSubmission = () => {
const formData = new FormData();
formData.append('File', selectedFile);
fetch(
'https://freeimage.host/api/1/upload?key=<YOUR_API_KEY>',
{
method: 'POST',
body: formData,
}
)
.then((response) => response.json())
.then((result) => {
console.log('Success:', result);
})
.catch((error) => {
console.error('Error:', error);
});
};
};
After recieving response from api service which is this part
.then((response) => response.json())
.then((result) => {
console.log('Success:', result);
})
.catch((error) => {
console.error('Error:', error);
});
You can set your state with the response url like this.
.then((response) => response.json())
.then((result) => {
console.log('Success:', result);
setPhoto(result.data.imageurl)
})
.catch((error) => {
console.error('Error:', error);
});
In the end you can use that image anywhere you want.
<img src={photo} />
I am learning react-native and have a question about fetching data and passing them to a text component.
I fetched my data from my node.js back-end but don't know how to pass this data to component. Below is the code that i have tried so far.
const TableView = () => {
const [details, setDetails] = useState('');
const getUserData = async () => {
fetch('https://----.herokuapp.com/getIncomePerUser', {
method: 'post',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({
email: data,
month: value,
}),
})
.then(response => response.json())
.then(response => {
console.log('Test');
console.log(response);
const array = response;
for (const i of array) {
const total = i.total;
setDetails(total);
console.log(total);
}
})
.catch(err => {
console.log(err);
});
});
};
useEffect(() => {
getUserData();
}, []);
return (
<Text Value={details}></Text> //I need to set my fetch data this text component
)
}
if you have an array of values and you want to show them you can use:
const TableView = () => {
const [details, setDetails] = useState('');
const getUserData = async () => {
fetch('https://----.herokuapp.com/getIncomePerUser', {
method: 'post',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({
email: data,
month: value,
}),
})
.then(response => response.json())
.then(response => {
setDetails(response.map(r => r.total));
})
.catch(err => {
console.log(err);
});
});
};
useEffect(() => {
getUserData();
}, []);
return (<>
{details.map((d, i) => <Text key={i}>{d}</Text>)}
</>)
}
if you have a single value just replace your text component with:
<Text>{details}</Text>
I'm new to react, i'm doing a small project where i have created a form and i want to add file also. Form having one API and for uploading files having another api.
handleSubmit = e => {
e.preventDefault();
const { firstName, LastName, phoneNumber} = this.state;
const data = {
firstName,
lastName,
phoneNumber
};
axios.post(`/api/Form`, data, {
headers: { 'Content-Type': 'application/json' }
})
.then(res => {
console.log(res)
console.log(res.data);
})
.catch((err) => {
console.log(err)
})
for files:
uploadFile = (files) => {
var formData = new FormData();
files.map((file, index) => {
formData.append(`file${index}`, file);
});
fetch('/api/uploadFiles', {
method: 'POST',
body: formData,
})
.then(response => response.json())
.then(success => {
})
.catch(error => console.log(error)
);
}
I couldn't able to figure it out how to write both apis in submit method. Can anyone help me in this query? I'm not sure how to give 2 apis in submit method.
Assign your formData to State
uploadFile = (files) => {
var formData = new FormData();
files.map((file, index) => {
formData.append(`file${index}`, file);
});
this.setState({file:formData});
}
Then Post your 2 API's in handleSubmit
handleSubmit = e => {
e.preventDefault();
const { firstName, lastName, phoneNumber, file} = this.state;
const data = {
firstName,
lastName,
phoneNumber
};
axios.post(`/api/Form`, data, {
headers: { 'Content-Type': 'application/json' }
}).then(res => {
console.log(res)
console.log(res.data);
}).catch((err) => {
console.log(err)
});
if(file) {
fetch('/api/uploadFiles', {
method: 'POST',
body: file,
}).then(response => response.json()).catch(error => console.log(error));
}
}
I'm fairly new to React and I've been trying to create a SignUp page, however, I'm stuck in this error. Can someone give me any indication on what I should do in order to solve this error?
Signup Method:
// = Action =
// Sign up
export const signup = user => {
return fetch(
`${API}/signup`,
{
method: 'POST',
headers: {
Accept:'application/json',
'Content-Type' : 'application/json'
},
body: JSON.stringify(user)
})
.then(response => {
return response.json();
})
.catch(err => console.log(err));
}
Rewrite Signup method (ps: I only changed the .catch handler)
`
// Sign up
export const signup = user => {
return fetch(
`${API}/signup`,
{
method: 'POST',
headers: {
Accept:'application/json',
'Content-Type' : 'application/json'
},
body: JSON.stringify(user)
})
.then(response => {
return response.json();
})
.catch(err =>
console.log(err));
return err;
}
`
You need to wrap up your fetch logic inside a Promise to return a value to the caller.
export const signup = user => {
return new Promise((resolve, reject) => {
fetch(`${API}/signup`,
{
method: 'POST',
headers: {
Accept:'application/json',
'Content-Type' : 'application/json'
},
body: JSON.stringify(user)
})
.then(response => response.json())
.then(jsonData => resolve(jsonData))
.catch(err => resolve({error: `something went wrong err : ${err}`}));
})
}
signup(user).then(data => {
if (data.error) {
// handle error case
} else {
// handle success case
}
})
Now your signup method will return a value. Your data variable won't be undefined anymore.
I hope it helps, feel free to add comments or ask me more details
I am trying to call 3rd party API, to fetch some data. I am getting the response in Postman, but not getting expected response when I execute my code.
I tried in 2 ways. Both ways I am getting "Promise pending".What could be the reason??
//request.js
Method 1
export const callSearchGiftsAPI = inputs => dispatch => {
dispatch(searchGifts());
let url = new URL(GIFT_SEARCH_API_URL),
params = {
apiKey: GIFT_SEARCH_API_KEY,
query: inputs.item,
country: 'us',
itemsPerPage: 3
};
Object.keys(params).forEach(key => url.searchParams.append(key, params[key]));
return new Promise((resolve, reject) => {
setTimeout(() => resolve(
fetch(url, {
method: 'GET',
// mode: 'no-cors',
headers: {
'Content-Type': 'application/json',
Authorization: `secret ${SECRET}`
}
})
.then(res => {
if (!res.ok) {
return Promise.reject(res.statusText);
}
console.log("hi", res.json());
return res.json();
})
.then(gifts => dispatch(searchGiftsSuccess(gifts)))
.catch(err => dispatch(searchGiftsError(err)))), 500)
});
}
Method 2:
export const callSearchGiftsAPI = inputs => dispatch => {
dispatch(searchGifts());
let url = new URL(GIFT_SEARCH_API_URL),
params = {
apiKey: GIFT_SEARCH_API_KEY,
query: inputs.item,
country: 'us',
itemsPerPage: 3
};
Object.keys(params).forEach(key => url.searchParams.append(key, params[key]));
fetch(url, {
method: 'GET',
// mode: 'no-cors',
headers: {
'Content-Type': 'application/json',
Authorization: `secret ${SECRET}`
}
})
.then(res => {
if (!res.ok) {
return Promise.reject(res.statusText);
}
console.log('result', res.json());
return res.json();
})
.then(gifts => dispatch(searchGiftsSuccess(gifts)))
.catch(err => dispatch(searchGiftsError(err)));
};
//form.js
class Form extend React.Component{
onSubmit(values) {
const inputs = Object.assign({}, values);
return this.props.dispatch(callSearchGiftsAPI(inputs));
}
//Remaining code
}
Also please note that I have installed CORS plugin in Chrome, to allow the request.If I disable it and add mode:'no-cors' I am getting as 401 unauthorized.What else am I supposed to do?
What happens is that you are creating a new Promise and returning it, but you are not waiting for it to resolve. You can either use then of the new async/await syntax to get the correct result :
onSubmit = async values => {
const inputs = Object.assign({}, values);
return await this.props.dispatch(callSearchGiftsAPI(inputs));
}
The code above will work with your first method.
Since your second method does not return anything, you will never get your result, you need to return your fetch's result and apply the code I gave above :
return fetch(url, {
This worked.
I was trying to put console.log in the wrong place and hence was not able to see the response properly.
export const callSearchGiftsAPI = inputs => dispatch => {
dispatch(searchGifts());
let url = new URL(GIFT_SEARCH_API_URL),
params = {
apiKey: GIFT_SEARCH_API_KEY,
query: inputs.item,
country: 'us',
itemsPerPage: 3
};
Object.keys(params).forEach(key => url.searchParams.append(key, params[key]));
console.log(url);
return fetch(url, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
Authorization: `secret ${SECRET}`
}
})
.then(res => {
console.log('result');
return res.json();
})
.then(response => {
console.log(response); // changed
dispatch(searchGiftsSuccess(response.items));
})
.catch(err => dispatch(searchGiftsError(err)));