How should i use asyncstorage.setItem in this fetch method? - react-native

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)

Related

Variables not registering in await function

What I'm trying to accomplish here is use req.body to pass the query arguments and when it hits the endpoint, the variables should be used in the create function of the Notion API. Unfortunately, the variables are registering as undefined. I figure that it's a scope issue, but I can't figure out how to structure this.
export default async function handler(req, res) {
const {
companyName,
email,
panelNames,
tags,
markers,
inquiry
} = req.body;
try {
await notion.pages
.create({
// use variables here
companyName: companyName //says undefined
}).then((result) => {
res.
})
} catch (e) {
console.log(e);
}
}
//Frontend code
const bodyQuery = {
companyName: "Example",
email: "example#gmail.com",
...
};
try {
await fetch("/api/v1/submit", headers)
.then((res) => {
return res.json();
})
.then((res) => {
setTests(res);
});
} catch (e) {
console.log("e:", e);
}
Because you did not pass bodyRequest to the request, so your backend can not receive data. Here's an example how to do it:
await fetch('/api/v1/submit', {
method: 'POST',
headers,
body: JSON.stringify(bodyRequest)
})
.then((res) => {
return res.json();
})
.then((res) => {
setTests(res);
});
And make sure your REST endpoint is POST. Hope it help!

how make put axios request with formData?

i tried to send data with text and file. i created formData to send it:
updateProduct(item){
let product = new FormData();
product.append('thumb', item.thumb)
product.append('weight', item.weight)
this.$store.dispatch('UPDATE_PRODUCT', product)
},
action in store:
UPDATE_PRODUCT({commit}, item){
const token = localStorage.getItem('token');
const config = {
headers: { Authorization: `Bearer ${token}`}
};
// console.log(token)
return axios.post(`${url}`, item, config)
.then((resp) => {
commit('UPDATE_PRODUCT_IN_STATE', resp)
return resp;
})
.catch((error) => {
console.log(error);
});
},
So i have 422 error. Why?

how to make the photo field optional in react native

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
)
};

Sqlite3 returning empty array with GET request in Express

I am trying to make a get request to an sqlite3 table, using Express, based on input from a form. The fetch request works and so does the db.all, but I receive a response as an empty array from rows. I tried req.query and req.params already. Not sure where the error is.
//server.js
app.get('/names/state', (req, res, next) => {
const stateValue = req.query.state;
db.all(`SELECT name FROM states WHERE name=$stateVal`,
{
$stateVal: stateValue
},
(err, rows) => {
res.send({rows:rows});
})
});
//script.js
const fetchOneBtn = (e) => {
e.preventDefault();
const stateVal = stateInputValue.value;
fetch(`/names/state?state=${stateVal}`)
.then(response =>{
if(response.ok){
return response.json();
}
}).then(names => {
console.log(names);
})
};
You can change your code in your backend with this code below:
app.get('/names/state', (req, res, next) => {
const stateValue = req.query.state;
var query = "SELECT name FROM states WHERE name = " + stateValue;
db.all(query, (err, rows) => {
if(err) {
console.log(err);
res.status(500).send(err);
}else {
res.send({rows});
}
})
});
Now, for your frontend, you can change with the code below:
const fetchOneBtn = async (e) => {
e.preventDefault();
const stateVal = stateInputValue.value;
try {
const response = await fetch(`/names/state?state=${stateVal}`, {
method: 'GET',
headers: {
'Content-Type': 'application/json'
},
});
console.log(await response.json());
return await response.json();
} catch(ex) {
console.log(ex);
}
};
I hope it can help you.

Losing connection during a fetch causes crash in React-Native app

If the internet connection is lost during a fetch in my react-native app I get Network request failed and the app crashes.
updateClientData() {
var cachedData = null;
AsyncStorage.getItem('cachedData').then((cachedDataString) => {
cachedData = JSON.parse(cachedDataString);
})
.done(() => {
if (cachedData) {
const base64 = require('base-64');
return fetch('https://...data.json', {
method: 'get',
headers: {
'Authorization': 'Basic '+base64.encode("..."),
}
})
.then( (response) => {
// never called:
return response.json();
})
.catch( (error) => {
//Shouldn't this catch network errors? It never gets called.
console.log('caught network error');
})
.then( (responseJSON) => {
//do something with the JSON
})
}
});
},
I would love to be able to handle this gracefully rather than have it crash. Any ideas?
For some reason, moving the AsyncStorage call out of this function made it work fine. I didn't actually need it until I had the result of the fetch anyway, so I moved it.
This works now:
updateClientData() {
const base64 = require('base-64');
return fetch(clientListURL, {
method: 'get',
headers: {
'Authorization': 'Basic '+base64.encode("..."),
}
})
.then( (response) => {
return response.json();
})
.catch( (error) => {
console.log('error...')
})
.then( (responseJSON) => {
// now do something with the JSON and the data from Async Storage
}
},