React Native AsyncStorage read the data after user input - javascript

I have a question, so i'm using AsyncStorage to store the user input data as a json format. However , while i'm checking whether the data are stored correctly using console.log, it always print out undefined, so i'm curious about how to access the data i store and print it out so that i can check if the data is correct? thanks!
Here's the json formate that i want the user input to store in
////JSON FORMAT////
const MyRecipeData = [
{
name: recipeName,
video_cover: selectedVideoCover,
video_url: UploadVideo,
servings: servingSize,
channel_name: channelName,
publish_date: uploadDate,
ingredients: ingredientsInput,
directions: directionsInput,
},
];
////JSON FORMAT////
and these are the function that called after the user pressing upload button, and i try to read it using getAllinput function, but not sure i did it right or not
////------- Save all DATA --------------------////
const SaveAllInput = async () => {
await AsyncStorage.setItem("MyRecipeData", JSON.stringify(MyRecipeData))
.then(() => {
alert("your Recipe " + MyRecipeData.name + " has been saved");
})
.catch(() => {
console.log("error");
});
getAllInput();
};
////------- Save all DATA --------------------////
////------- READING THE DATA THAT UPLOAD PREVIOUSLY-------- /////
const getAllInput = async () => {
try {
const NewRecipeData = await AsyncStorage.getItem("MyRecipeData");
NewRecipeData !== null ? JSON.parse(NewRecipeData) : null;
console.log(NewRecipeData);
return NewRecipeData;
} catch {
console.log(error);
}
};
////------- READING THE DATA THAT UPLOAD PREVIOUSLY-------- /////
the console.log(NewRecipeData) print out [{}] in my terminal, seems like i did not read my data properly
i tried to use getItem to read it out, but instead i got undefined or [{}]

const NewRecipeData = await AsyncStorage.getItem("MyRecipeData");
NewRecipeData !== null ? JSON.parse(NewRecipeData) : null;
You using const and you are redefining the variable, try to console.log like this :
const NewRecipeData = await AsyncStorage.getItem("MyRecipeData");
console.log(NewRecipeData);
You are caliing getAllInput(); without await
const SaveAllInput = async () => {
const MyRecipeData = [
{
name: recipeName,
video_cover: selectedVideoCover,
video_url: UploadVideo,
servings: servingSize,
channel_name: channelName,
publish_date: uploadDate,
ingredients: ingredientsInput,
directions: directionsInput,
},
];
await AsyncStorage.setItem('MyRecipeData', JSON.stringify(MyRecipeData))
.then(() => {
alert('your Recipe ' + MyRecipeData.name + ' has been saved');
})
.catch(() => {
console.log('error');
});
await getAllInput();
};

Related

ref is stacking in sockets react native

Im trying to build chat application using sockets and everything is working except when im trying to add new session I beilieve it is stacking the reference but I don't know what I'm missing
here is my code
const [sessions, setSessions] = useState([]);
const userSocketRef = useRef(null);
useEffect(() => {
async function getUser() {
const user = await authStorage.getUser();
const URL = "ws://192.168.1.176:3001/" + "users";
if (userSocketRef.current === null) {
userSocketRef.current = io(URL, {
auth: { user: user.uuid },
transports: ["polling", "websocket"],
});
userSocketRef.current.on("disconnect", () => {
console.log("disconnected");
});
userSocketRef.current.on("connect", () => {
console.log("connected");
});
userSocketRef.current.onAny((event, ...args) => {
console.log("event");
});
userSocketRef.current.on("connect_error", (err) => {
console.log("connect_error");
});
}
}
console.log("current sessions after handle: "+Object.keys(sessions))
getUser();
if (userSocketRef.current !== null ) {
userSocketRef.current.on(
"private message",
(message, sessionUuid) => {
console.log("private message");
handleUpdateSession(message, sessionUuid);
}
);
userSocketRef.current.on("new session", async (session) => {
console.log(Object.keys(sessions));
console.log(Object.keys(session));
await handleNewSession(session);
});
}
}, [sessions]);
useEffect(() => {
async function getSessions() {
const user = await authStorage.getUser();
const ret = await getUserSessions(user?.uuid);
setSessions(ret.data.reverse());
}
getSessions();
}, []);
const handleNewSession = async (newSession) => {
console.log("current sessions: " + Object.keys(sessions));
console.log("new session: " + Object.keys(newSession));
setSessions([newSession, ...sessions]);
};
const handleUpdateSession = (message, sessionUuid) => {
try {
console.log(sessionUuid, Object.keys(sessions));
const temp = sessions;
const session = temp.find((s) => s.uuid === sessionUuid);
session.messages.push(message);
const filteredSessions = temp.filter((s) => s.uuid !== sessionUuid);
setSessions([session, ...filteredSessions]);
} catch (error) {
console.log(error);
}
};
now when i try to open new session it works great and I can send messages but when the user tries to send message it duplicates so many times and it gets errors because they are the same key I tried to debug and here is my conclusion
LOG current sessions after handle:
LOG current sessions after handle:
LOG connected
LOG event
LOG []
LOG ["uuid", "createdAt", "updatedAt", "expirationDate", "name", "device", "messages"]
LOG current sessions:
LOG new session: uuid,createdAt,updatedAt,expirationDate,name,device,messages
LOG current sessions after handle: 0
LOG event
LOG private message
LOG a0d35995-8d79-433a-aab9-1d911d20e756 []
LOG [TypeError: undefined is not an object (evaluating 'session.messages')]
LOG private message
LOG a0d35995-8d79-433a-aab9-1d911d20e756 ["0"]
LOG current sessions after handle: 0
as you can see the useEffect loads twice I don't know why then i trigger new session and then session set to the state then I try to send message from the sender you notice that the session.messages is undefined then it finds the session
I don't know why does it stack like this
thanks

How to get the value of a variable out of the scope of the arrow function which created it

So, i have this code:
client.on("messageCreate", async (msg) => {
if (msg.content.startsWith("-p")) {
if (!msg.member.voice?.channel) return msg.channel.send("Por favor...");
const connection = joinVoiceChannel({
channelId: msg.member.voice.channel.id,
guildId: msg.guild.id,
adapterCreator: msg.guild.voiceAdapterCreator,
});
google
.youtube("v3")
.search.list({
key: process.env.YOUTUBE_TOKEN,
part: "id",
q: msg.content.slice(3),
maxResults: 1,
})
.then((response) => {
const { data } = response;
let link = "https://www.youtube.com/watch?v=" + data.items.id.videoId;
});
let args = msg.content.slice(3);
let stream = await play.stream(args);
let resource = createAudioResource(stream.stream, {
inputType: stream.type,
});
let player = createAudioPlayer({
behaviors: {
noSubscriber: NoSubscriberBehavior.Play,
},
});
player.play(resource);
connection.subscribe(player);
}
});
And I would like to use the value of the variable "link", which is a string, as a parameter for the method play.stre(args)
I'm don't fully understand how to get that done
Also, if possible I would like to find a way to store that value too inside an array outside the whole:
*client.on('messageCreate' , async msg => {... ...})*
You most likely want to call play.stream from within the then callback of list:
google.youtube("v3")
.search.list({
key: process.env.YOUTUBE_TOKEN,
part: "id",
q: msg.content.slice(3),
maxResults: 1,
})
.then(async (response) => {
const { data } = response;
let link = "https://www.youtube.com/watch?v=" + data.items.id.videoId;
let stream = await play.stream(link);
});
Like this, you'll make sure that you actually have a value set for link when using it to call stream.

Not able to push my data in an json server

This is a local JSON server you can see on this URL
http://localhost:3003/CourseList/1
My hooks
const [subjectName,setsubjectName]=useState(
{
id: "",
subjectname: "Aptitude",
chapter: [
{
chapter1: "",
topic: [
{
topic1: ""
}
]
}
]
}
);
function when I click on add button which will check if it matches the id of a prop then it will perform the task
const addSubject = async id => {
console.log("id "+id);
axios.get(`http://localhost:3003/CourseList/`)
.then((res)=>{
res.data.map((list,index)=>{
if(list.id===props.id){
console.log(list.subject)
list.subject.push(subjectName);
}
})
})
.catch((error)=>{
console.log(error);
})
};
How can I push new data in the subject array? I am getting nothing
Here's the solution
const addSubject = async id => {
console.log("id "+id);
try{
const {data} = await axios.get("http://localhost:3003/CourseList")
data.map(async(item)=>{
if(item.id===id){
console.log(item);
item.subject.push(subjectName);
await axios.put(`http://localhost:3003/CourseList/${id}`,item)
}
})
const check= await axios.get(http://localhost:3003/CourseList/${id})
console.log(check)
}catch(err){
console.log(err.message)
}
};
If you're using a JSON-server it should have a default endpoint for PATH/PUT your new object. You need to send the Content/Type: application/json in your request header and set the jsonServer.bodyParser in your server.

How to get push key in firebase?

I want to get the Key generated when I push data to Firebase database. I want to handle them with my own function,
So the issue is when the user fills the form he sends the data to our real-time DB, contained in this data are some images (optional), and I don't need to let the image object empty in DB, so how to handle this, and when the user needs to send an image I want to save this image in the same Order, not in New Order.
Node
Here is my function
handleOrder = () => {
const { nameOfProblem, description, userId, imageOfPrblem, providerId } = this.state;
const PushData = firebase.database().ref("request/" + providerId + "/" + userId + "/orders/");
const ref = firebase.storage().ref("users/" + userId + "/UserImageOrders/" + path);
let file = imageOfPrblem.uri;
const path = "img_" + imageOfPrblem.fileName;
var newOrderRef = PushData.push({
nameOfProblem: nameOfProblem,
description: description,
});
if (file) {
let keyG = newOrderRef.key; // Key Generated with .push()
PushData.child(keyG).update({ // didn't updated the key generated just add new element with new key !!
imageOfPrblem: imageOfPrblem
});
ref.put(file).then(() => {
console.log("File uploaded..")
});
}
}
handleImages = () => {
const options = {
title: "Select Images!",
storageOptions: {
skipBackup: true,
path: "images"
}
};
ImagePicker.showImagePicker(options, response => {
console.log("Response = ", response);
if (response.uri) {
this.setState({ imageOfPrblem: response });
}
if (response.didCancel) {
console.log("User cancelled image picker");
} else if (response.error) {
console.log("ImagePicker Error: ", response.error);
} else if (response.customButton) {
console.log("User tapped custom button: ", response.customButton);
alert(response.customButton);
}
});
};
This seems to work fine for me:
var ref = firebase.database().ref("/55912103");
var newChildRef = ref.push({ firstChild: true });
console.log("new key: "+newChildRef.key);
ref.child(newChildRef.key).update({ secondChild: true });
After running this code, I end up with this JSON in the new child whose key gets logged:
"-LdgLWu_wBNNicFlPDGj" : {
"firstChild" : true,
"secondChild" : true
}
Live demo: https://jsbin.com/hovoleh/edit?js,console
Live JSON: https://stackoverflow.firebaseio.com/55912103.json?print=pretty
Update: if you just want to write both the existing data and new data to a new location:
var newOrderRef = PushData.push({
nameOfProblem: nameOfProblem,
description: description,
});
if (file) {
let keyG = newOrderRef.key; // Key Generated with .push()
PushData.child(keyG).update({
nameOfProblem: nameOfProblem,
description: description,
imageOfPrblem: imageOfPrblem
});
ref.put(file).then(() => {
console.log("File uploaded..")
});
}
The push ID from any Firebase snapshot ref is in ref.name().
I know it's been a while since the author created a post but maybe someone will find it useful.
The above answers are a bit wrong because, for example, after: newChildRef
var ref = firebase.database().ref("/55912103");
var newChildRef = ref.push({ firstChild: true });
newChildRef <--- promise
ref = rdb.ref('name_of_your_ref');
var childRef = ref.push({
IdUser: currentUserId,
ProductCategory: pCategory,
ProductDescription: pDesc,
ProductId: pId,
ProductName: pName,
ProductPrice: pPrice,
ProductQuantity: pQuan
}).catch(err => console.log(err.message));
childRef.then(item => {
ref.child(item.key).update({
IdKey: item.key
}).then(() => history.push('/delivery/basket'));
});
Greetings, Matthew

store each api response in an array in React

I am using metaweather.com API to build a Web Application. I want to show 6 cities on the home page; I guess I have to call the API 6 time and push the data in an array like allCitiesDetails. How I have to do that? If there is a better way, please tell me. Here is my code :
state = {
city: {
cityname: this.props.value
},
woeid: '',
todayWeather: [],
weatherDetails: [],
allCitiesDetails: []
};
getCity = (cityName) => {
var self = this;
axios
.get('https://www.metaweather.com/api/location/search/?query=' + cityName)
.then(response => {
self.setState({
woeid: response.data[0].woeid
});
self.getWeather(response.data[0].woeid);
})
.catch(function(error) {
alert('No results were found. Try changing the keyword!');
});
}
getWeather = async (woeid) => {
const { data: weatherDetails } = await axios.get(
'https://www.metaweather.com/api/location/' + woeid
);
this.setState({
weatherDetails,
todayWeather: weatherDetails.consolidated_weather[0]
});
}
You should make 6 different promises and use Promise.all to get the weather of all 6 cities in parallel. You can do this as :
const getWeatherFromWoeid = cityName => axios.get(`https://www.metaweather.com/api/location/${woeid}`);
....
const p1 = getWeatherFromWoeid(woeid1);
const p2 = getWeatherFromWoeid(woeid2);
const p3 = getWeatherFromWoeid(woeid3);
const p4 = getWeatherFromWoeid(woeid4);
const p5 = getWeatherFromWoeid(woeid5);
const p6 = getWeatherFromWoeid(woeid6);
Promise.all([p1,p2,p3,p4,p5,p6])
.then(([result1, result2, result3, result4, result5, result6]) => {
...set result in the state
})
.catch((err) => {
...handle error
})
Also, always use catch if you're using promises or async
instead of using state inside the api call...
self.setState({
woeid: response.data[0].woeid
});
you can push the values in dummy array then outside the api call u can set state.

Categories

Resources