I am new in react native, trying to assign fetch API response value to a local variable. But outside function shows an undefined value of the variable.
Here is code
const {
diesel_data
} = this.state
let currentHMR
let previous_HMR
let previous_EstEngHours
let isViolationPass_HMR
let asset_id = diesel_data[0].diselRequisitionDetails[0].asset_id
let current_hmr = diesel_data[0].diselRequisitionDetails[0].current_hmr
let requisitionId = diesel_data[0].requisitionId
this._indicator.startActivity()
fetch(url + 'Norms/DieselHmrViolation/' + asset_id + '/' + current_hmr + '/' + requisitionId, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
},
})
.then((response) => response.json())
.then((json) => {
this._indicator.stopActivity()
var list = json;
console.log(list)
if (!isBlank(list)) {
currentHMR = list.currentHMR
previous_HMR = list.previous_HMR
previous_EstEngHours = list.previous_EstEngHours
isViolationPass_HMR = list.isViolationPass_HMR
}
})
.catch((error) => {
console.error(error);
});
console.log('currentHMR', currentHMR)
I think you can do like this, wait until executing fetch (maybe you have to move this inside a async function)
let data;
await fetch('https://reqres.in/api/users/2', {
method: 'GET',
headers: {
'Content-Type': 'application/json',
}
})
.then(res => res.json())
.then(res => data = res)
.catch(err => console.log(err))
console.log('data', data);
Related
I am trying to upload an image to the bunnycdn with fetch / PUT. I am trying to put the image into the body but it doesn't work this way. Is there anything i can change?
const uploadpicture = async () => {
console.log("uploadpic")
//here use then props.route.params.image etc
let randomid = uuid()
let bodyy = new FormData()
bodyy.append("image",props.route.params.image.uri)
const options = {
method: 'PUT',
headers: {
'content-type': 'application/octet-stream',
AccessKey: '185e0bd5-1e29-492e-811d6cde3520-4ebe-4c15'
},
body: bodyy
};
fetch(`https://storage.bunnycdn.com/premvanaprogr/${currentUserObject.uid}/${randomid}.jpg`, options)
.then(response => response.json())
.then(response => console.log(response))
.catch(err => console.error(err))
}
in React native can anyone tell me how to make the responsePath optional thats how i make it optional using && but it is not working in case of photo field can anyone help me out below are the codes.first is of redux how i send the data using formdata and 2nd is of component where i called this api function of redux.
redux//
export const addMember = (formValues, actions, key, resourcePath) => {
return async dispatch => {
const token = await AsyncStorage.getItem('userToken');
const formdata = new FormData();
formdata.append('name', formValues.name);
formdata.append('age', formValues.age);
formdata.append('relation', formValues.relation);
formdata.append('gender', key);
formValues.mobile && formdata.append('mobile', formValues.mobile);
formValues.blood_group &&
formdata.append('blood_group', formValues.blood_group);
formValues.height && formdata.append('height', formValues.height);
formValues.weight && formdata.append('weight', formValues.weight);
formValues.email && formdata.append('email', formValues.email);
resourcePath && formdata.append('photo', resourcePath);
console.log(formdata, 'for mdata');
let response = await fetch(
'https://theeasylab.com/admin/api/auth/add-family-member',
{
method: 'post',
body: formdata,
headers: {
Authorization: `Bearer ${token}`,
'Content-Type': 'multipart/form-data',
},
},
)
.then(res => {
return res;
})
.catch(error => {
actions.setErrors(error?.response?.data.error);
return error.response;
});
dispatch({
type: 'ADD_MEMBER',
payload: response,
});
};
};
component //
submitAddMemeber = (values, actions) => {
this.props
.addMember(
values,
actions,
this.state.itemValue.key,
this.state.resourcePath
)
};
i want to add the async storage method to save my json response,
but i don't know how to add there specifically
i have already tried like this
UserRegisterationFunction = () => {
const { UserName } = this.state;
const { UserEmail } = this.state;
const { UserPassword } = this.state;
fetch('http://192.168.1.7/test/user_registration.php', {
method: 'POST',
headers: {
'Accept' : 'application/json',
'Content-Type' : 'application/json'
},
body: JSON.stringify({
name: UserName,
email: UserEmail,
password: UserPassword
})
}).then((response) => response.json())
.then((responseJson) => {
AsyncStorage.setItem('token', responseJson)
// this._onValueChange(STORAGE_KEY, responseData.id_token),
Alert.alert(responseJson);
}).catch((error) => {
console.log(error)
});
i am getting my alert successfully but i don't know how should i add the responseJson or if i have used it correctly or not
You can use the asynchronous system or save successfully without using it.
To run asynchronously:
.then(async (responseJson) => {
await AsyncStorage.setItem('token', responseJson.id_token);
Alert.alert(responseJson);
}).catch((error) => {
console.log(error)
});
If your responseJson data is this:
Object {
id_token : "myid"
}
Use the getItem function on the following screen to check the value.
async componentDidmount() {
const tokens = await AsyncStorage.getItem('token');
alert(tokens); // You can see 'myid'
}
The JSON response is an object and you can't store the object directly in AsyncStorage. You can only store the object by converting it into a string.
To store the object:
AsyncStorage.setItem('KEY', JSON.stringify(object))
To retrieve the object:
const jsonObjectString = AsyncStorage.getItem('KEY')
const jsonObject = JSON.parse(jsonObjectString)
I need to fetch data from pass parameter in below format, because when test in Postman then only this format gives response.
"json": {"model":"DB11 AMR","modelyear":"2019","locale":"AA"}
Can you please help to fetch data from below server url.
https://vhapp.azurewebsites.net/myAMLModelSelection
Below is my code
var url = 'http://vhapp.azurewebsites.net/myAMLModelSelection'
try {
let response = fetch(url, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
"json" : { "locale": "AA", "model" : "DB11 AMR", "modelyear" : "2019" }
})
})
.then(res => res.text()) // convert to plain text
.then(text => {
console.log(text)
alert(text)
var res = text.substring(1, text.length-2);
var obj = JSON.parse(res);
alert(obj.cars[0].name)
})
.catch((error) => {
console.error(error);
});
} catch (errors) {
console.log(errors);
}
Here is my response which i need
({"cars":[{"name":"DB11 AMR","content":{"guide":"http://cdntbs.astonmartin.com/360ss/OwnersGuides/KY53-19A321-AC.pdf","assets":[{"intAssetId":"115","intVehicleId":"1","strType":"pdf","strName":"Accessories Brochure","strDescription":null,"strLocation":"http://cdntbs.astonmartin.com/360ss/iPad/myaml/brochures/Accessories Brochure English - 706435-PK.pdf","intVersion":"1","intOrder":"1"}]}}]});
You can fetch the data using JS fetch API.
export async fetchMyData(){
try{
let f = await fetch('https://vhapp.azurewebsites.net/myAMLModelSelection',{method:'GET'})
let data = await f.json();
return data;
}catch(err){
console.log(err)
}
}
And Call this method in your component like:
import {fetchMyData} from './file_name'
fetchMyData().then((response)=>{console.log(response)})
I'm currently trying to chain API requests to retrieve user information with React Native. The problem that I am running into is that the first fetch request goes provides the response that I'm looking for, but the chained request hangs up.
I've been able to narrow this down by running the API on my machine and here's what the problem is. When the first request is made, the headers in the config object are passed through without issue. When the second request is made, the X-Tenant-Name header is passed through, but for some reason the Authorization header is lost in the process, and therefore the request fails.
Here's the function making the requests:
async componentWillMount() {
const { authToken, selectedUser, tenant } = this.props;
const config = {
method: 'GET',
headers: {
'X-Tenant-Name': tenant,
'Authorization': 'Bearer ' + authToken
}
}
await fetch(URL + '/users/' + selectedUser.id, config)
.then(response => response.json())
.then(response => {
this.setState({ user: response.data });
const children = response.data.relationships.following_tips.data;
if (children.length) {
for (let i = 0; i < children.length; i++) {
fetch(URL + '/tips/' + children[i].id, config)
.then(response => response.json())
.then(response => console.log(response))
.done();
}
}
})
.done();
}
Any ideas?
I think your problem is being caused because your are forgetting to pass config to the second fetch. Try this one:
async componentWillMount() {
const { authToken, selectedUser, tenant } = this.props;
const config = {
method: 'GET',
headers: {
'X-Tenant-Name': tenant,
'Authorization': 'Bearer ' + authToken
}
}
await fetch(URL + '/users/' + selectedUser.id, config)
.then(response => response.json())
.then(response => {
this.setState({ user: response.data });
const children = response.data.relationships.following_tips.data;
if (children.length) {
for (let i = 0; i < children.length; i++) {
fetch(URL + '/tips/' + children[i].id, config) //Add config to this fetch too.
.then(response => response.json())
.then(response => console.log(response))
.done();
}
}
})
.done();
}