How do I set content to be equal to a variable I made? - html-helper

How do I set content to be equal to a variable I made?
request.setRequestHeader('Content-type', 'application/json');
const params = {
username: "username",
avatar_url: "",
content: ,
}

If you are in javascript this would be like :
const params = {
username: "username",
avatar_url: "",
content: inputVal,
}

Related

Why is there a validation error for submitting this formik?

My problem is that I receive a validation error on my server when trying to update my user and product collection in mongodb using formik on my front end.
I add a new product as logged in user. All of the authentication is working with JWT token.
"ValidationError: Product validation failed: title: Path title is required., description: Path description is required., price: Path price is required., location: Path location is required., condition: Path condition is required., category: Path category is required."
I've looked everywhere on stack of, and tried everything for 30+ hours. If anyone could help, I'd appreciate it. I feel bad for asking this novice question, but I've been struggling.
Here is my front end code using formik and axios :
const schema = yup.object().shape({
title: yup.string().required('Title is required'),
description: yup.string().required('Description is required'),
price: yup.number().required('Price is required').positive('Price must be a positive number'),
location: yup.string().required('Location is required'),
condition: yup.string().required('Condition is required'),
category: yup.string().required('Category is required'),
});
const addProductFormik = useFormik({
initialValues: {
title: "",
description: "",
price: "",
location: "",
condition: "",
category: "",
},
validationSchema: schema,
onSubmit: async (values) =\> {
try {
const formData = new FormData();
formData.append('title', values.title);
formData.append('description', values.description);
formData.append('price', values.price);
formData.append('location', values.location);
formData.append('condition', values.condition);
formData.append('category', values.category);
console.log(formData.get('title'));
console.log(formData.get('price'));
const url = `http://localhost:3005/product/${user._id}/add-product`;
const config = {
headers: { Authorization: 'Bearer ' + token }
};
console.log(config);
const response = await axios.post(url, formData, config);
console.log(response);
const newProduct = response.data.product;
console.log(newProduct);
// dispatch(addProduct(newProduct));
} catch (error) {
console.log(error)
console.error(error);
}
},
});
Here is my controller function to update my mongo database :
export const createProduct = async (req, res, next) => {
try {
const id = req.params.userId;
const user = await User.findById(id);
if (!user) {
return res.status(404).json({ message: "User not found" });
}
console.log('user was found')
const createdProduct = new Product({
title: req.body.title,
description: req.body.description,
price: req.body.price,
location: req.body.location,
condition: req.body.condition,
category: req.body.category,
});
console.log(createdProduct);
console.log('product was created')
console.log(createdProduct._id);
try {
createdProduct.save();
user.products.push(createdProduct._id);
Product.insertMany(createdProduct);
// JWT token signing
const token = jwt.sign({ userId: user.id }, 'supersecretkey', { expiresIn: '1h' });
res.status(201).json({ product: createdProduct, token });
} catch (err) {
const error = new HttpError(
'Creating product failed, please try again.',
500
);
return next(error);
}
console.log('controller function works!');
} catch (error) {
console.error(error)
res.status(404).json({ message: error.message });
}
};
Here is my Product Schema :
import mongoose from "mongoose";
const Schema = mongoose.Schema;
const ProductSchema = new Schema({
title: {
type: String,
required: true,
},
description: {
type: String,
required: true,
},
price: {
type: Number,
required: true,
},
location: {
type: String,
required: true,
},
condition: {
type: String,
required: true,
},
category: {
type: String,
required: true,
enum: ["Cars", "Electronics", "Clothing", "Furniture", "Other"],
},
seller: {
type: Schema.Types.ObjectId,
ref: "User",
},
createdAt: {
type: Date,
default: Date.now,
},
});
const Product = mongoose.model("Product", ProductSchema);
export default Product;
Here is my User Schema :
import mongoose from "mongoose";
const Schema = mongoose.Schema;
const UserSchema = new Schema({
firstName: {
type: String,
required: true,
min: 2,
max: 50,
},
lastName: {
type: String,
required: true,
min: 2,
max: 50,
},
email: {
type: String,
required: true,
unique: true,
},
password: {
type: String,
required: true,
},
location: {
type: String,
required: true,
},
products: [
{
type: Schema.Types.ObjectId,
ref: "Product",
},
],
createdAt: {
type: Date,
default: Date.now,
},
});
const User = mongoose.model("User", UserSchema);
export default User
Now when I submit the form, there is no error on the front end. I get a 201 response and when I console log the newProduct in the addProductFormik, this is what it says :
_id: '63f27485ed59ed8c6fdff654', createdAt: '2023-02-19T19:12:05.981Z'}
createdAt: "2023-02-19T19:12:05.981Z"
_id: "63f27485ed59ed8c6fdff654"
On the back end, i get this error : "ValidationError: Product validation failed: title: Path title is required., description: Path description is required., price: Path price is required., location: Path location is required., condition: Path condition is required., category: Path category is required."
Now if you look at the console logs made in the controller function, these are the console logs that are logged on the server,
user was found
{
_id: new ObjectId("63f27485ed59ed8c6fdff654"),
createdAt: 2023-02-19T19:12:05.981Z
}
product was created
new ObjectId("63f27485ed59ed8c6fdff654")
controller function works!
So within my controller function, it finds the user in params, the createdProduct is only shown as a new ObjectId and not with all of its fields (title, description, price, etc). Somehow, it makes it through all the try blocks and console logs the controller function works. But my products collection and user collection (user.products) is not updated and I get that validation error.
Since you're using formData, you need to pass in the Content-Type through Axios headers when posting:
headers: { "Content-Type": "multipart/form-data" },
The default type is application/xml which won't work with your data.
You'll also need to make sure your backend is configured to handle that data coming in. body-parser is commonly used for this with Express.
Here's a simple configuration:
const express = require('express')
const bodyParser = require('body-parser')
const app = express()
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json({ limit: '10mb' ))

TypeError: Cannot read properties of undefined (reading 'country') Whenever I search for a city

I am using Open weather map and Reactjs.
The problem is found in my WeatherContainer component.
I want my search bar to work. But whenever I search for a city I get this error:
I have tried changing the API key but it does nothing.
The code error line is pointing at :
I get my data like this:
WeatherContainer.tsx:
const [weather, setWeather] = useState({
city: "",
country: "",
temperature: 0,
description: "",
icon: "",
humidity: "",
feels: "",
visibility: "",
pressure: "",
longitude: "",
latitude: "",
windSpeed: "",
});
useEffect(() => {
if (fetchedData)
setWeather({
city: fetchedData.name,
country: fetchedData.sys.country,
temperature: Math.floor(fetchedData.main.temp - 273),
description: fetchedData.weather[0].description,
icon: `http://openweathermap.org/img/wn/${fetchedData.weather[0].icon}.png`,
humidity: fetchedData.main.humidity + "%",
feels: Math.floor(fetchedData.main.feels_like - 273) + "°C",
visibility: fetchedData.visibility + "m",
pressure: fetchedData.main.pressure + "hPa",
longitude: fetchedData.coord.lon,
latitude: fetchedData.coord.lat,
windSpeed: fetchedData.wind.speed + "m/s",
});
}, [fetchedData]);
Edit:
This is how I defined fetchedData
export const WeatherContainer = ({
fetchedData,
error,
}: {
fetchedData: any;
error: string;
}) => {
const [weather, setWeather] = useState({
city: "",
country: "",
temperature: 0,
description: "",
icon: "",
humidity: "",
feels: "",
visibility: "",
pressure: "",
longitude: "",
latitude: "",
windSpeed: "",
});
useEffect(() => {
if (fetchedData)
setWeather({
city: fetchedData.name,
country: fetchedData.sys.country,
temperature: Math.floor(fetchedData.main.temp - 273),
description: fetchedData.weather[0].description,
icon: `http://openweathermap.org/img/wn/${fetchedData.weather[0].icon}.png`,
humidity: fetchedData.main.humidity + "%",
feels: Math.floor(fetchedData.main.feels_like - 273) + "°C",
visibility: fetchedData.visibility + "m",
pressure: fetchedData.main.pressure + "hPa",
longitude: fetchedData.coord.lon,
latitude: fetchedData.coord.lat,
windSpeed: fetchedData.wind.speed + "m/s",
});
}, [fetchedData]);
I used this API https://openweathermap.org/current. I just tried to follow this documentation so I copied the link to API they have.
Edit # 2
This is the file Where I make the connection:
const API_KEY = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
export const getWeatherCoordinates = async (
LAT: number,
LON: number
): Promise<any> => {
const API_URL = `https://api.openweathermap.org/data/2.5/weather?lat=${LAT}&lon=${LON}&appid=${API_KEY}`;
const respCoordinates = await fetch(API_URL);
const dataCoordinates = await respCoordinates.json();
return dataCoordinates;
};
export const getWeatherSearch = async (CITY: string): Promise<any> => {
const API_CITY = `https://api.openweathermap.org/data/2.5/weather?q=${CITY}&appid={API_KEY}`;
const respCity = await fetch(API_CITY);
const dataCity = await respCity.json();
return dataCity;
};
The API response is :
{"cod":401, "message": "Invalid API key. Please see http://openweathermap.org/faq#error401 for more info."}
Based on the error image you posted and the source code, it seems like missed a $ sign in front of {API_KEY} in getWeatherSearch :
export const getWeatherSearch = async (CITY: string): Promise<any> => {
const API_CITY = `https://api.openweathermap.org/data/2.5/weather?q=${CITY}&appid=${API_KEY}`; // <- HERE
const respCity = await fetch(API_CITY);
const dataCity = await respCity.json();
return dataCity;
};

How to update nested object values with a reducer function in React?

Hello I have a very complex form with many nested objects and I am wondering how to update a field in the nested objects without writing one million lines of code, this is what I currently have. I have heard about the library called immer but know nothing about it.
this is the initial value of the object
const initialFormState = {
name: "",
address: {
street1: "",
street2: "",
city: "",
state: "",
zip: "",
country: "",
gps: {
lat: "",
lng: ""
}
},
clientId: "",
contact: {
userId: "",
firstName: "",
lastName: "",
jobTitle: ""
},
isActive: true,
requiresAction: true,
details: {
lastInspectionDate: "",
lastMaintenanceDate: "",
employeesTrained: 0,
phone: "",
companyManager: {
name: "",
title: "",
phone: "",
email: ""
},
companyOwner: {
name: "",
title: "",
phone: "",
email: ""
},
companyContact: {
name: "",
title: "",
phone: "",
email: ""
},
companyType: "",
locations: 0,
foo: 0,
bar: 0,
foo2: ""
}
}
and my reducer function and state variables
const [formState, dispatch] = useReducer(formReducer, initialFormState)
const formReducer = (prevState: any, action: any) => {
switch (action.type) {
case 'update-name':
return { ...prevState, name: action.payload}
console.log()
break
case 'update-address':
return { ...prevState, address: { ...prevState.address, [action.field]: action.payload}}
break
case 'update-contact':
return { ...prevState, contact: { ...prevState.contact, [action.field]: action.paylod}}
break
case 'update-client-id':
return { ...prevState, clientId: action.payload}
break
case 'update-isActive':
return { ...prevState, isActive: action.payload }
break
case 'update-requiresAction':
return { ...prevState, requiresAction: action.payload}
break
case 'update-details':
return { ...prevState, details: { ...prevState.details, [action.field]: action.payload}}
}
}
but everytime I go to update the contact object, I keep getting undefined. This is what I am passing in the onChange for the text fields, I will use street line 1 as an example
onChange={(e) => { dispatch({ type: 'update-contact', field: 'street1', payload: e.target.value })}}

Nested Mutation in graphql

I'm trying to implement GraphQL+MongoDb into a project and I'm stuck at nesting.
I have to do a meal history for an User. I've managed to create the User type+resolver+query but i'm stuck at getting a meal for that User.
I've got this typeDefs:
import { gql } from 'apollo-server';
export const typeDefs = gql`
type User {
id: Int!
CNP: String
firstName: String!
lastName: String!
email: String!
birthday: String
sex: String
Studii: String
Adresa: String
}
type Aliment {
id: String!
foodName: String!
}
type Foods {
aliment: Aliment!
quantity: Int!
}
type Meal {
id: String!
user: User!
currentmeal: [Foods!]!
date: String!
}
input AlimentInput {
id: String
foodName: String
}
input FoodsInput {
aliment: AlimentInput
quantity: String
}
input UserInput {
id: Int
CNP: String
firstName: String
lastName: String
email: String
birthday: String
sex: String
Studii: String
Adresa: String
}
input MealInput {
id: String
user: UserInput
currentmeal: [FoodsInput]
date: String
}
type Query {
getUsers: [User]
getUserInfo(id: Int): User
getMeals: [Meal]
}
type Mutation {
createMeal(
id: String!
user: UserInput
currentmeal: [FoodsInput]
date: String
): Meal
}
`;
and this resolver:
import { Users, Meals } from '../models/users.js';
export const resolvers = {
Query: {
getUsers: async () => {
console.log('1');
return Users.find({}).then((users) => {
console.log('2');
return users.map((user) => ({
id: user.id,
firstName: user.firstName,
lastName: user.lastName,
email: user.email,
}));
});
},
getUserInfo: async (parent, args) => {
console.log('b');
return Users.findOne({ id: args.id }).then(async (user) => {
return {
id: user.id,
firstName: user.firstName,
lastName: user.lastName,
email: user.email,
};
});
},
getMeals: async () => {
return Meals.find({}).then((meals) => {
return meals.map(async (meal) => {
console.log(meal);
return {
id: meal.id,
user: meal.user,
currentmeal: meal.currentmeal,
date: meal.date,
};
});
});
},
},
Mutation: {
createMeal: async (id, user, currentmeal, date) => {
return await Meals.create({
id: id,
user: user,
currentmeal: currentmeal,
date: date,
});
},
},
};
and these schemas:
import mongoose from 'mongoose';
const { Schema } = mongoose;
const { model } = mongoose;
const userSchema = new Schema({
id: { type: String, required: true, index: { unique: true } },
firstName: { type: String, required: true },
lastName: { type: String, required: true },
userName: { type: String, required: true },
email: { type: String, required: true },
jobTitle: { type: String, required: false },
});
const alimentSchema = new Schema({
id: { type: String, required: true, index: { unique: true } },
foodName: { type: String, required: true },
});
const foodsSchema = new Schema({
aliment: { type: Schema.Types.ObjectId, ref: 'users' },
quantity: { type: String },
});
const mealSchema = new Schema({
id: { type: String, required: true, index: { unique: true } },
user: { type: Schema.Types.ObjectId, ref: 'users' },
currentmeal: [foodsSchema],
date: { type: String },
});
export const Users = model('users', userSchema);
export const Aliments = model('aliments', alimentSchema);
export const Meals = model('meals', mealSchema);
When I use the getMeals query i want to get something like:
Meal{
id: 1
user:{
id: Int!
CNP: String
firstName: String!
lastName: String!
email: String!
birthday: String
sex: String
Studii: String
Adresa: String
}
currentmeal: [
{
aliment: {
id:1
foodName:Chicken breasts
}
quantity: 100
},
{
aliment: {
id:2
foodName:French Fries
}
quantity: 200
}
]
date: notimportant
}
I've been searching for several hours on nesting for GraphQL but found nothing useful.
I've managed to populate the database somehow and this is what i currently have:
import { MongoClient } from 'mongodb';
const populate = async () => {
const connstring ="";
const client = await MongoClient.connect(connstring, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
const db = client.db('test');
let id = 0;
let meals = [];
for (id = 1; id < 90; id++) {
const user = await db.collection('users').findOne({ id: id });
const currentmeal = [];
let aliment1 = await db.collection('aliments').findOne({ id: id });
let aliment2 = await db.collection('aliments').findOne({ id: id });
currentmeal.push({
aliment: aliment1,
quantity: 200 - id,
});
currentmeal.push({
aliment: aliment2,
quantity: 200 - id,
});
const date = JSON.stringify(Date.now());
meals.push({
id,
user,
currentmeal,
date,
});
}
await db.collection('meals').insertMany(meals);
client.close();
};
populate();
this is how Users look:
this is how aliments look:
and this is how meals look:
I think that in the meals collection i should have user's _id instead of the user object, same for aliment in the currentmeal Array

How to merge/add variable in angular

Below is my user object. Once i submit form i am getting values for it along with priPhone , mobilePhone.
this.user = {
isActive: 1,
contactDetails: {
name: { }
},
};
}
mobilePhone:any={phoneNumber: '',type:'Mobile'};
primaryPhone:any={phoneNumber: '',type:'Primary'};
I have to set mobilePhone, primaryPhone details to User Object.
So that i want final object like this.
this.user = {
isActive: 1,
contactDetails: {
name: { }
},
phoneNumbers: [{
phoneNumber: '',
type: 'Primary'
}, {
phoneNumber: '',
type: 'Mobile'
}]
};
How to do it ?
This should work in javascript.
this.user.phoneNumbers = [];
this.user.phoneNumbers.push(mobilePhone);
this.user.phoneNumbers.push(primaryPhone);
or simply
this.user.phoneNumbers = [mobilePhone, primaryPhone];

Resources