React, NodeJS, MySQL setValue of date in date input - mysql

I need to setValue of a date input that I retrieve from the DB(MySQL).
My Model has two date pickers (checkIn and CheckOut) as string on React and Node, at mySQL it is set to date type.
This is my useEffect:
const { register, handleSubmit, formState, setValue } = useForm<VacationModel>();
const navigate = useNavigate();
const params = useParams();
useEffect(() => {
const id = +params.vacationId; // Same name as router parameter.
vacationsService.getOneVacation(id)
.then(vacation => {
setValue("vacationId", vacation.vacationId);
setValue("destination", vacation.destination);
setValue("description", vacation.description);
setValue("checkIn", vacation.checkIn);
setValue("checkOut", vacation.checkOut);
setValue("price", vacation.price);
setValue("image", vacation.image);
})
.catch(err => notifyService.error(err));
}, []);
How is it possible to set the correct dates from the DB in my Edit component?
Thank you.

Found the answer.
At the database I formatted the date from %d/%m/%Y to %Y-%m-%d.
After that I had to make the string go to this specific format by using:
setValue("checkIn", new Date(vacation.checkIn).toISOstring().split('T');
setValue("checkOut", new Date(vacation.checkOut).toISOstring().split('T');
And then the values were inserted correctly.
Hope it will help others.

Related

The user entered date changes when stored in mongodb, how to store it in original state?

I am making a practice project on a restaurant website that has an option of table reservation. The date-time entered in the form by the user changes when stored in MongoDB due to the UTC time-saving system of MongoDB. In India, the time is UTC+5:30 so it changes accordingly. How do I modify the time entered by the user so that it can be saved in its original state? I am new to MongoDB and mongoose so I am not well versed with the techniques which can be used.
Eg: Suppose the user entered the date-time as 26-5-22 8:27 pm
In mongodb, it saves as ISO(2022-05-26T14:57:00Z)
MY js code for MongoDB is below:
const mongoose = require('mongoose');
main().catch(err => console.log(err));
async function main(){
await mongoose.connect('mongodb://localhost:27017/HamdansEatery');
}
const reservationSchema= new mongoose.Schema({
fname: String,
lname: String,
tel: Number,
email: String,
no_of_persons: Number,
date_time: Date
})
const Reservation = mongoose.model("Reservations",reservationSchema);
//----------------------------------------->
app.post('/reserve_a_table', (req,res) => {
let yourData = new Reservation(req.body);
yourData.save().then(()=>{
res.send("Data has been saved successfully!");
}).catch(() => {
res.status(400).send("Data not saved due to some issues.");
})
})
The frontend is HTML form with (input type = datetime-local)
I saw some related questions but couldn't find one for a user-entered date and time.
How should I progress? How can I modify the Date SchemaType such that it can in a way add 5:30hrs while saving in MongoDB so I can get the result I want i.e. time in Indian Standard Time?

How to initialize checkbox based on dynamic value in React

I am trying to initialize a checkbox to either checked or unchecked based on a value in local storage (chrome extension). I was trying to trigger a function on load that checks the a value in local storage and returns a Boolean value. Since there are multiple checkboxes I need to pass the element id to the function as well.
Here is a semi-pseudo code version of what I was thinking :
const getChecked = (el: any): boolean => {
val = el.id from local storage;
return val;
}
const App = () => (
<div className="App">
<input
type="checkbox"
id="checkboxID"
defaultChecked={getChecked}
/>
</div>
);
But something like this doesn't work because defaultChecked={getChecked} gives me the error " Type '(el: any) => boolean' is not assignable to type 'boolean | undefined'."
Any ideas on what to do?
Thanks.
Please try using checked parameter, instead of defaultChecked.
To get the value from local storage I would suggest you to use a function like this:
const getChecked = (el:any) => {
return JSON.parse(localStorage.getItem("el.id"))
};
Make sure that el.id value is true or false in local storage.

How to store n number of inputs into an array using mysql in express.js

Hi I a beginner to the web development
I wanted to accept n number of the instance(n is inputted by the user) from the user and then store those values in an array-like structure so that my frontend can have access to it. Can this be done using mysql ?. I was reading StackOverflow posts that mentioned that it is not a good idea to use MySQL for this. However I am already kind of deep into my project so I want to clarify this.
Is this feasible using MySQL?
I guess you want to store something like object or array of something
let's say that in your front end there is a form with input and button
where the input is Add More Columns and the input is value so in your backend you will get an array of objects like
[
{ question: '1', answer: 'Answer1' },
{ question: '2', answer: 'Answer2' },
{ question: '3', answer: 'Answer3' },
{ question: '4', answer: 'Answer4' }
]
you can make a table
id | userId | payload
where id is generated by SQL
userId that you injected in the token (or something else to relate the user with his payloads)
and payload that contains the information that you need to store
const saveUserPayLoads = async (req, res) => {
const { payloads } = req.body;
const { id } = req.user
const data = []
for(payload of payloads) data.push(DBModule.create({ payload: JSON.stringify(payload), userId: id }))
return res.status(201).json({
message: 'Done',
success: true,
data
})
}

Displaying Node MySQL Results in React Using State

My node.js MySQL query returns a single row wrapped in [RowPacketData] which I can normally access the ID field using results[0].ID.
However, when I store the result in React state (using hooks) it does not work. I can access the result object, but not fields within it.
function MyReactComponent() {
const [dbEntry, setDbEntry] = useState();
useEffect(() => {
const fetchData = async () => {
const result = await queryFunc(`SELECT * FROM table LIMIT 1`);
console.log(result[0]); // <-- Works (shows [RowDataPacket] object)
console.log(result[0].ID); // <-- Works (shows ID)
setDbEntry(result);
};
fetchData();
}, []);
console.log(dbEntry[0]); // <-- Works (shows [RowDataPacket] object)
console.log(dbEntry[0].ID); // <-- TypeError: Cannot read property '0' of undefined
return (
<p>
{dbEntry[0].ID} // <-- How do I render here?
</p>
)
}
What's going on here? I have a feeling React is coercing the result object somehow, but I can't figure it out...
When you need to display data that comes from an async font(API calls for example), it's possible (actually almost certain) that it won't be available by the time the first render occurs, to solve that there is actually a few things you could do:
Placeholder state
You could have a model of what the data will look like described as your initial state, so properties won't be undefined anymore:
const [state, setState] = useState({
data:[
{name: ''}
]
})
Assuming that your data will have this format accessing state.data[0].name won't throw an error. This could be useful in some cases but I personally don't like the approach.
Conditional Render
At each render you should check for a condition and only if satisfied render the piece of code:
return(
<>
<div>Title</div>
{Boolean(state.data.length) && <div>{state.data[0].name}</div>}
</>
)
Suspense
That one is brand new, if you have a component tha't need to perform side effects before render it's content, you should have a fallback content to be displayed while the async action is being perform.
<Suspense fallback={<span>Loading</span>}>
<MYAsyncComponent />
</Suspense>

Is there a way to fetch data in database from a Ruby-on-Rails models

I have a rails app running alongside with a rails API, there is a constant value for DAYS_LIMIT in config/initializers/constants.rb
DAYS_LIMIT = 40
DEFAULT_PRICE = 1.29
but now in the app i added an input field so that the user decide his DAYS_LIMIT.
So i want to fetch that value from the database from inside the API models.
I have placed breakpoints and can see that inside the API controller, the data is transfered from the app but not to the models.
edited as a question requested , it's a React-on-Rails app , here is the code where the new input field is save to the database (i have removed the other fields so the question look shorter)
export const saveChannel = (files) => {
return async (dispatch, getState) => {
const { channel } = getState();
const {rss_podcast_days} = channel;
const { image } = files;
const save = id ? updateChannel : createChannel;
const sub_required = subscription_required !== undefined ? subscription_required : false;
const formData = new FormData();
formData.append('channel[rss_podcast_days]', rss_podcast_days || '');
if (Object.keys(image).length) {
formData.append('channel[image]', image);
}
const channelId = await dispatch(save(formData, id));
dispatch(fetchChannel(id));
return id;
};
};
from the app controller
podcast_list = RestClient.get("#{ENV['URL_API']}/api/#{#channel.id.as_json}/podcast/list")
#podcasts = JSON.parse(podcast_list.body)
#podcasts = #podcasts.sort.reverse.to_h
this is from the API controller witch the data is transfered from the app
def index
podcasts = #channel.podcasts.published.list(params[:page], params[:items_per_page], params[:ordered_in])
render json: Podcasts::Normalizer.normalize(podcasts, #channel.station.default_podcast_price)
end
and here from the API model that i want to fetch data instead of the constants.
scope :by_days_limit, -> {with_tags.more_recent_than(Date.today - DAYS_LIMIT.days).ordered}
it should take today date minus the value (DAYS_LIMIT) from user input, but for now i get undefined local variable or method if i try to fetch directly
Bro if your class has constant like DAYS_LIMIT you can access it using that class itself for example,
class Demo
DAYS_LIMIT = 5
end
you can access that constant by Demo.DAYS_LIMIT in controller or else wherever you need it.
good luck!
ok , so i finally got it, i don't know if i should delete this thread or just tell how i did it. If it's inapropriate just tell me and i will delete this entire thread.
So here is how i did it, in the API controller i had to add my fetch so that the arguments (list) knows what i am talking about. #channel.days_limit
def index
podcasts = #channel.podcasts.published.list(params[:page], params[:items_per_page], params[:ordered_in], #channel.days_limit)
render json: Podcasts::Normalizer.normalize(podcasts, #channel.station.default_podcast_price)
end
then in the def list of the models, i added days_limit has argument
def list(page = nil, nb_items_per_page = 40, ordered_in = 'desc', days_limit)
ordered_in = ordered_in.in?(['asc', 'desc']) ? ordered_in : 'desc'
page.blank? ? by_days_limit(days_limit) : by_page(page, nb_items_per_page, ordered_in)
end
and finally in the scope of the models, i pass in the new argument
scope :by_days_limit, -> (days_limit) {with_tags.more_recent_than(Date.today - days_limit.days).ordered}
Now the user input from the app is passing to the models via the controller.