React LocalStorage issue not stored in localstorage - mysql

I am using Local Storage for my login page
but my variables not storing in the local storage I don't know why....
I am using the following code on my button click....
But the APi i am using is correct... It works fine
res.data.status gives true or false,Inside Axios .then => If is used for correct username and password and else is used for incorrct user
This is my Code:
async function handleSubmit(e) {
var url = 'http://localhost/project/login.php?name='+name+"&price="+price;
const formData = new FormData();
formData.append('avatar',"hi")
await axios.post(url, formData)
.then(res => {
if(!res.data.status){
localStorage.setItem('username', name);
alert(res.data.message);
}else{
alert(res.data.message);
}
})
}

if your variable is not stored in the localStorage. that's because of the condition you have. also as you're sure that your API is working fine and you can successfully make a request and receive a response. then the issue is with the condition. because from your code. you're making conditions only if the request is not successful. you don't have the condition for success.
async function handleSubmit(e) {
var url = 'http://localhost/project/login.php?name='+name+"&price="+price;
const formData = new FormData();
formData.append('avatar',"hi")
await axios.post(url, formData)
.then(res => {
if(!res.data.status){ <= remove the !
localStorage.setItem('username', name);
alert(res.data.message);
}else{
alert(res.data.message);
}
})
}

Related

How to pass updated set State value in axios request as params

I'm a beginner in react native, I'm trying to get user information from mysql database through an axios API get request.
Once logged in, I stored email address in AsyncStorage and later want to use that email address from AsyncStorage as params or parameters to get the user details.
I wrote a code which set initial state of the setState as 'na'. Please help me how I can pass the email address from AsyncStorage as params or parameters.
Here is my code.
// to load email address
const [SessionEmail, setSessionEmail] = useState('na');
// to load users info
const [users, setUsers] = useState([]);
useFocusEffect(
React.useCallback(() => {
getUsername();
getUsersInfoFromAPI();
}, [])
);
// to get the session username from localstorage
const getUsername = async () => {
try {
const username = await AsyncStorage.getItem('Username')
if (username !== null) {
setSessionEmail(username);
}
} catch (e) {
console.log(e);
}
}
// API Calling user details
const getUsersInfoFromAPI = async () => {
await axios.get(`https://myapi.co.in/api/user/?email=${SessionEmail}`)
.then(response => {
setUser(response.data);
})
.catch(error => {
console.log(error);
});
}
After the page is rendered, and I load page from metro, I can see the parameters have been sent to server.
Update your code in this way:
useFocusEffect(
React.useCallback(() => {
getUsername();
}, [])
);
Instead of saving your email to state, sent it to function directly but if you are using it for other reason you can still save it but call function while getting username from AsyncStorage with username parameter like below.
// to get the session username from localstorage
const getUsername = async () => {
try {
const username = await AsyncStorage.getItem('Username')
if (username !== null) {
getUsersInfoFromAPI(username);
}
} catch (e) {
console.log(e);
}
}
// API Calling user details
const getUsersInfoFromAPI = async (email) => {
await axios.get(`https://myapi.co.in/api/user/?email=${email}`)
.then(response => {
setUser(response.data);
})
.catch(error => {
console.log(error);
});
}
const [users, setUsers] = useState([]);
here you can use like this
const [users, setUsers] = useState();
hope this will help you

Set image in HTML from API request node.js

I have an API request that returns the image of the product that had been saved in the database in the form of buffer in MONGODB. The API returns the image and I want this image as source to my html element. How do I do that?
The API request is:
router.get('/product/avatar/:id', async (req, res) => {
try{
const product = await Product.findById(req.params.id)
if(!product || !product.avatar){
throw new Error()
}
// console.log('product avatar')
res.set('Content-Type', 'image/png')
res.send(product.avatar)
} catch(e) {
res.status(404).send()
}
})
And this is how I was trying to assign that image to my HTML
the code snippet given below is a part of the javascript used to render information on webpage from database.
var picId = data[i].name + 'Image'
// console.log(data[i]._id)
fetch('/product/avatar/'+data[i]._id, {
method: 'GET'
}).then((res) => {
return res.json()
}).then((data) => {
// picId.value = data
// document.getElementById(picId).src = data
console.log(data)
})

how to make a post request inside async function?

At the end of the waterfall-dialog in "summary" (i.e., the last if statement) i want to automatically make a post request without making an API call in Postman, is eventListener the way? How to include it?
async summaryStep(step) {
if (step.result) {
// Get the current profile object from user state.
const userProfile = await this.userProfile.get(step.context, new UserProfile());
userProfile.name = step.values.name;
//the same for other step values(email, doctor, date)
let msg = `you want a date with dr. ${userProfile.doctor} , and your name is ${userProfile.name}.`;
if (userProfile.date !== -1) {
msg += `you have an appointment the: ${userProfile.date}.`;
}
await step.context.sendActivity(msg);
let msg1 = `"${userProfile.date}"`;
if (msg1) {
let z = JSON.stringify(userProfile.name);
//and also the other rows to go in the database(email, doctor, date)
var name = JSON.parse(z);
//and also the other rows to go in the database(email, doctor, date)
//this actually works but only if i use postman
var urlencoded = bodyparser.urlencoded({ extended: false });
app.post('/id', urlencoded, (req, res) => {
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
mysqlConnection.query("INSERT INTO users(name, email, doctor, date) VALUES('" + userProfile.name + "','" + userProfile.password + "','" + userProfile.doctor + "','" + userProfile.date + "')", function (err, result, rows) {
if (err) throw err;
console.log("Yeah! record inserted");
console.log(name);
res.send(result);
});
});
const port = process.env.PORT || 8080;
app.listen(port, () => console.log(`Listening on port ${port}..`));
}
} else {
await step.context.sendActivity('Thanks. Your profile will not be kept. Push enter to return Menu');
}
return await step.prompt(CONFIRM_PROMPT3, `is that true? ${step.result}`, ['yes', 'no']);
// this if statement should "fire" the post request...
if (step.result == 'yes') {
return await step.context.sendActivity(`we will contact you soon ${userProfile.password}.`);
}
return await step.endDialog();
}
Per my understanding , you want to know how to call an POST API from Azure bot async function. Pls try the code below in your async summaryStep function to send the post request based on your requirement.
var rp = require('request-promise');
var options = {
method: 'POST',
uri: 'http://localhost:8080/id',
body: {
fieldCount:0,
affectedRows:1,
//your other body content here...
},
json: true,
headers: {
'content-type': 'application/json' //you can append other headers here
}
};
await rp(options)
.then(function (body) {
console.log(body)
})
.catch(function (err) {
console.log(err)
});
}
Hope it helps .
A
nd if there is any further concerns or misunderstand , pls feel free to let me know.
The answer is to move your app.post API endpoint to your index.js file where your bot is already running on a server. Simply spin up a new "server" and "port" making the endpoint available. Then, in your summaryStep (axiosStep in my example), make your API call using Axios, request-promise, or what have you, to post your data. When the API is hit, the data will be passed in and processed.
In the code below, when the API is hit the passed in data is used in a sendActivity posted back to the bot. In your case, your passed in data would be used for the database call in which you could use the returned response in the sendActivity.
Your code would look something like the following. Please note, the post actions are simplified for the sake of the example. You would need to update the post actions to make your mySql queries. This sample also makes use of restify for the server (standard for Bot Framework bots) and uses the same port as the bot, but this can easily be updated to use Express and/or another port.
Hope of help!
index.js
[...]
const conversationReferences = {};
const bodyParser = require('body-parser');
server.post('/id', async (req, res) => {
const { conversationID, data, name } = req.body;
const conversationReference = conversationReferences[ conversationID ];
await adapter.continueConversation(conversationReference, async turnContext => {
var reply = `${ data }. Thanks, ${ name }`;
await turnContext.sendActivity(reply);
});
res.writeHead(200);
res.end();
});
mainDialog.js
async axiosStep ( stepContext ) {
const conversationID = stepContext.context.activity.conversation.id;
try {
const response = await axios.post(`http://localhost:3978/id`, {
data: "Yeah! Record inserted",
name: "Steve",
conversationID: conversationID
})
console.log(response);
} catch (error) {
console.log(error);
}
return stepContext.next();
}

How can I make multiple API calls with the same key

I'm working on my Project and currently I have one API call to spoonacular's search by recipe GET request. I want to add the search by video GET Request but I seem to having problems getting both to render at once into the DOM. How can I fix this issue?
const apikey = '';
const urls = { search:'https://api.spoonacular.com/recipes/complexSearch',
videos: 'https://api.spoonacular.com/food/videos/search'
};
function queryParams(params) {
const queryItems = Object.keys(params).map(key=>`${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`)
return queryItems.join('&');
}
///render results
function getRecipe(tacos,maxResults){
const params ={
query: tacos,
number: maxResults,
};
const queryString = queryParams(params)
const url = urls+'?'+queryString +'&apiKey='+ apikey;
console.log(url);
fetch(url)
fetch(urls.search)
.then(response =>{
if(response.ok){
return response.json();
}
throw new Error(response.statusText);
})
.then(responseJson => displayResults(responseJson))
.catch(err =>{
$('#js-error-message').text(`Something went wrong: ${err.message}`);
});
}
Your urls is an object containing two strings. You need to treat it as such and make two separate calls.
You should have a fetch(urls.search) and fetch(urls.videos) call, each with their own response chain.
I'm not sure this code is doing what you think it is:
const url = urls+'?'+queryString +'&apiKey='+ apikey;
You'll need to append the queryString and apiKey to each string within urls separately. Something like
const searchUrl = urls.search+'?'+queryString +'&apiKey='+ apikey;
const videosUrl = urls.videos+'?'+queryString +'&apiKey='+ apikey;

Pulling Data from JSON with React-Native

What's wrong with this picture ? :-)
I'm trying to pull values from my wordpress JSON objects.
I must not be addressing them the correct/proper way with React-Native.
Can someone direct me as to how to form the correct console log statement ?
As it stands right now, the variable 'theMediaLink' is coming up 'undefined' in the console log. :-(
state={
data:[]
}
fetchData = async() => {
const response = await
//response
fetch('http://example.com/wp-json/wp/v2/posts/')
//posts
const posts = await response.json();
this.setState({data:posts});
const theMediaLink = `https://example.com/wp-json/wp/v2/media/` + `${this.state.data.featuredmedia}`;
console.log('theMediaLink_value: ', theMediaLink);
}
I should add that the fetch is retrieving data as I use it later on with a FLATLIST to pull the posts. My question is I must be misforming the call, but how ?
This is more an issue of understanding of React rather than React Native.
Try this:
fetchData = async () => {
const URL = 'http://example.com/wp-json/wp/v2/posts/'
const response = await fetch(URL)
const posts = await response.json();
return this.setState({ data : posts }, () => {
const { data } = this.state
const theMediaLink = `https://example.com/wp-json/wp/v2/media/${ data.featuredmedia }`;
console.log('theMediaLink_value: ', theMediaLink);
});
}
Since setState is asynchronous, you won't be able to see the state update right away, that's why the callback is for.
More info on how to setState asynchronously and use its value after right here