Vue.js - Store data into session - html

How do I store my dadta in a session so I can access it in any page? And only destroy the data whenever the page is closed.
Vue.js:
new Vue({
el: '#item-data',
data () {
return {
data:[],
selectedUser:'',
itemCart: [],
quantity: ''
}
},
mounted () {
**** API CALL ****
}
})
.then((response) => {
// handle success
this.data = response.data.items
removeLoader();
})
.catch(function (error) {
// handle error
console.log(error);
})
.then(function () {
// always executed
});
},
methods:{
sendInfo(items) {
this.selectedUser = items;
},
addCart: function(cartdets){
this.itemCart.push({cartdets});
console.log(cartdets);
}
}
})
The data i want to store into a session is itemCart[].

Related

Delete an image of a post stored in a backend folder when i delete a user of a social network application

I have a problem on my application, it is a social network. The user can create a post with a message and an image, stored in a backend images folder thanks to Multer. I use sequelize and MySql. When I delete a post, the image is indeed deleted in the images folder since I use multer in my post deletion function so everything goes well but when I delete the author, since I go through a relationship between tables so that when I delete a user, their posts are deleted. This works but in this case the images are not deleted from the folder they are stored in, since Multer is not in the loop. How do I get the images to be deleted from the images folder too in this specific case? Thank you for your help !
`
// Template for the Post table
const User = require("../models/User");
const Sequelize = require("sequelize");
const database = require("../config/database");
const Post = database.define("post", {
content: { type: Sequelize.STRING, allowNull: false },
image: { type: Sequelize.STRING, allowNull: true },
likes: { type: Sequelize.INTEGER, allowNull: false, default: 0 },
});
module.exports = Post;
// Relationship with the User table
User.hasMany(Post, { onDelete: "CASCADE", foreignKey: "userId" });
Post.belongsTo(User, { onDelete: "CASCADE" });
`
`
// deletePost function
exports.deleteOnePost = (req, res, next) => {
Post.findOne({ where: { id: req.params.id } })
.then((post) => {
if (!post) {
return res.status(404).json({
error: new Error("Post non trouvé !"),
});
}
if (post.userId === req.auth.userId || req.auth.userAdmin) {
if (post.image) {
const filename = post.image.split("/images/")[1];
fs.unlink(`images/${filename}`, () => {});
}
Post.destroy({ where: { id: req.params.id } })
.then(() => res.status(200).json({ message: "Post sans supprimé" }))
.catch((error) => res.status(400).json({ error }));
} else {
return res.status(403).json({
error: new Error("Requête non autorisée !"),
});
}
})
.catch((error) => res.status(500).json({ error }));
};
`
#Anatoly Thank you very much for your help, I'm sorry, I'm a beginner, I tried to adapt what you sent me to the method I use. I don't use the async/await method much and don't know much about it. Do you think I'm getting closer to the solution with what i made ? thanks again !
`
exports.deleteUser = (req, res, next) => {
const userId = req.params.id;
User.findOne({ where: { id: userId } }).then((user) => {
if (!user) {
return res.status(404).json({
error: new Error("User not found!"),
});
}
});
const userPosts = User.getAllPosts();
const postImages = posts.map((x) => x.image).filter((x) => x);
User.destroy({ where: { id: userId } })
.then((post) => {
Post.findOne({ where: { userId } })
.then((post) => {
Post.destroy({ where: { userId } }).then((res) =>
res.status(200).json({
message: "User is deleted",
})
);
for (const image of postImages) {
const filename = image.split("/images/")[1];
fs.unlink(`images/${filename}`, () => {});
}
})
.catch((error) =>
res.status(400).json({
error,
})
);
})
.catch((error) => res.status(500).json({ error }));
};
`
I don't see how Multer is related to a file deletion. It only helps you to store them. Any way you just need to get all posts of a certain user and delete them and a user in a transaction and then delete their images in a cycle:
// I did not use try/catch for simplicity
exports.deleteUser = async (req, res, next) => {
// get the user id somehow (req.params or the request context, for instance)
const userId = ...
const user = await User.findById(userId);
if (!user) {
return res.status(404).json({
error: new Error("User not found!"),
});
}
const userPosts = await user.getPosts();
const postImages = poists.map(x => x.image).filter(x => x);
// here 'sequelize' is the Sequelize instance, you used to register models
await sequelize,transaction(async transaction => {
await Post.destroy({ where: { userId } })
await User.destroy({ where: { id: userId } })
});
for (const image of postImages) {
const filename = image.split("/images/")[1];
fs.unlink(`images/${filename}`, () => {});
}
res.status(200).json({ message: "User is deleted" }))
}
I come back to put the fonction that works with my method, i often use ".then()" ".catch()", many thanks to Anatoly for helping me to find the solution, here is the result of my work :
exports.deleteUser = (req, res, next) => {
User.findOne({ where: { id: req.params.id } })
.then((user) => {
if (!user) {
return res.status(404).json({
error: new Error("user not found !"),
});
}
// I get all the posts of the author
Post.findAll({ where: { userId: req.params.id } })
.then((posts) => {
// I start a loop in the posts of the author to find the posts with an image
posts.forEach((post) => {
if (post.image) {
// I erase the files in the images backend directory
const filename = post.image.split("/images/")[1];
fs.unlink(`images/${filename}`, () => {});
}
// Now i can erase the author
User.destroy({ where: { id: req.params.id } })
.then(() =>
res.status(200).json({
message: "User erased !",
})
)
.catch((error) =>
res.status(400).json({
error,
})
);
});
})
.catch((error) =>
res.status(400).json({
error,
})
);
})
.catch((error) => res.status(500).json({ error }));
};

Node.js - CRUD API multi delete ID's from SQL

I have small project with ReactJS + NodeJS + mySQL.
I can't create-receive correct request for multi delete by IDs.
This how I sent request from React to Node ==>
const deleteProductsByIds = () => {
let ids = [];
stateProducts.forEach((d) => {
if (d.select) {
ids.push(d.id);
}
});
axios
.delete(`http://localhost:5000/products/${ids}`)
.then((data) => {
console.log(data);
getProducts();
})
.catch((err) => alert(err));
};
this how I receive request in Node(sequelize)
router.delete('/:ids', deleteProducts);
export const deleteProducts = async (req, res) => {
try {
await Product.destroy({
where: {
id: []
}
});
res.json({
"message": "ProductS Deleted"
});
} catch (error) {
res.json({ message: error.message });
}
in logs I have this data and by message everything fine, but products(301,302,303,304) not deleted.
config: {url: 'http://localhost:5000/products/301,302,303,304',
method: 'delete', headers: {…},
transformRequest: Array(1), transformResponse: Array(1), …}
data: {message: 'ProductS Deleted'}
I try
where: {
id: req.params.ids
}
but ids value undefind
also I try:
const ids = req.params
try {
await Product.destroy({
where: {
id: ids
}
});
message: "Invalid value { ids: '301,302,303,304' }"}
but receive error message.
usual delete request by ID working without any problem.
For example:
export const deleteProduct = async (req, res) => {
try {
await Product.destroy({
where: {
id: req.params.id
}
});
res.json({
"message": "Product Deleted"
});
} catch (error) {
res.json({ message: error.message });
}
}
Please help me, because I can't find so much information about multi delete request with React-Node-mySQL.

How to fetch JSON results from multiple APIs using redux

I have three different APIs that I am fetching JSON results from and I want to dispatch all three of them using React Native Redux. I am trying to implement a server side search filter that gets the response from all three APIs. How can I do this?
actions.ts
// API 1
export const getCountries = () => {
try {
return async (dispatch) => {
const response = await axios.get(`${BASE_URL}`);
if (response.data) {
dispatch({
type: GET_COUNTRIES,
payload: response.data,
});
} else {
console.log("Unable to fetch data from the API BASE URL!");
}
};
} catch (error) {
console.log(error);
}
};
// API 2
export const getStates = () => {
try {
return async (dispatch) => {
const response = await axios.get(`${BASE_URL_STATES}`);
if (response.data) {
dispatch({
type: GET_STATES,
payload: response.data,
});
} else {
console.log("Unable to fetch data from the API BASE URL!");
}
};
} catch (error) {
console.log(error);
}
};
// API 3
export const getCounties = () => {
try {
return async (dispatch) => {
const response = await axios.get(`${BASE_URL_COUNTIES}`);
if (response.data) {
dispatch({
type: GET_COUNTIES,
payload: response.data,
});
} else {
console.log("Unable to fetch data from the API BASE URL!");
}
};
} catch (error) {
console.log(error);
}
};

Adding JSON data to React

I have been able to pull data from an API that I built using MongoDB and Express, but am having trouble rendering the nested data to my React component.
For example, if I type in <p>{restaurant.cuisine}</p> I am able to retrieve Burgers, American, but if I try and access {restaurant.status.delivery}, I get an error that says:
Cannot read property 'delivery' of undefined.
But if I {console.log(restaurant.status} I can see the object? I tried turning the object into an array using Object.values, but that didn't work either.
The same thing happens if I try to access the nested objects in {restaurant.images} and {restaurant.geometry}.
Here's a copy of my React hook:
import { useReducer, useEffect } from 'react';
import axios from 'axios';
const ACTIONS = {
MAKE_REQUEST: 'make-request',
GET_DATA: 'get-data',
ERROR: 'error',
};
function reducer(state, action) {
switch (action.type) {
case ACTIONS.MAKE_REQUEST:
return { loading: true, restaurant: [] };
case ACTIONS.GET_DATA:
return {
...state,
loading: false,
restaurant: action.payload.restaurant,
};
case ACTIONS.ERROR:
return {
...state,
loading: false,
error: action.payload.error,
restaurant: [],
};
default:
return state;
}
}
export default function useFetchSingleRestaurant({ id }) {
const [state, dispatch] = useReducer(reducer, {
restaurant: [],
loading: true,
});
useEffect(() => {
dispatch({ type: ACTIONS.MAKE_REQUEST });
axios
.get('http://localhost:4444/restaurants/' + id)
.then((res) => {
dispatch({
type: ACTIONS.GET_DATA,
payload: { restaurant: res.data.restaurant },
});
})
.catch((e) => {
dispatch({
type: ACTIONS.ERROR,
payload: { error: e },
});
});
}, [id]);
return state;
}
I'm accessing it in my SingleRestaurant component:
function SingleRestaurant({ match }) {
const { restaurant } = useFetchSingleRestaurant({ id: match.params.id });
return (
<p>{restaurant.status.delivery}</p>
)
}
And then here's my backend setup as well:
showRestaurant = async (req, res) => {
const restaurant = await Restaurant.findById(req.params.id)
.populate({ path: 'reviews', populate: { path: 'author' } })
.populate('author');
if (!restaurant) {
req.flash('error', 'Restaurant not found.');
return res.redirect('/restaurants');
}
res.send({ restaurant });
};
Until your server request returns restaurant it will be set as the default [] that you have set.
An empty array does not have a property of status, so hence the error.
if you change your default to null:
const [state, dispatch] = useReducer(reducer, {
restaurant: null,
loading: true,
});
And then check for a value:
function SingleRestaurant({ match }) {
const { restaurant } = useFetchSingleRestaurant({ id: match.params.id });
if (!restaurant) return 'Loading'
return (
<p>{restaurant.status.delivery}</p>
)
}
You could also pass back the loading state from your hook and then do a check on that.

receiving a json response with vue.js2 in laravel

sending a request and getting response which bases on it i want to chege the status and display something different, can't figure out what's the problem, the route seems to be working fine and I'm receiving a response which looks like this
I'm trying to access this using Vue component and I'm getting that error status is not defined, here is my Vue component
<script>
export default {
mounted() {
axios.get('/userfound/' + this.profile_user_id)
.then(function (response) {
console.log(response);
this.status = response.data.status;
})
.catch(function (error) {
console.log(error);
});
},
props: ['profile_user_id'],
data(){
return {
status: ''
}
},
methods:{
add_friend(){
// this.loading = false
axios.get('/add_friend/' + this.profile_user_id)
.then(function (response) {
console.log(response);
if (response.data == 1) {
this.status = 'waiting'
}
})
.catch(function (error) {
console.log(error);
});
}
}
}
</script>
why am i getting this error: TypeError: cannot read property 'status' of undefined ..
i've tried "this.status = response.body.status" and "this.status = response.data.status" but neither is working
I believe there is an issue with the scope of a variable. Try below answer:
<script>
export default {
mounted() {
var self = this;
axios.get('/userfound/' + self.profile_user_id)
.then(function (response) {
console.log(response);
self.status = response.data.status;
})
.catch(function (error) {
console.log(error);
});
},
props: ['profile_user_id'],
data(){
return {
status: ''
}
},
methods:{
add_friend(){
// you can do same here as well
var self = this;
axios.get('/add_friend/' + self.profile_user_id)
.then(function (response) {
console.log(response);
if (response.data == 1) {
self.status = 'waiting'
}
})
.catch(function (error) {
console.log(error);
});
}
}
}
</script>