I have this code below which will allow me to get the user selected option but the problem i couldn't access the local variable ,
the code is below
let gender=""
const handleAddrTypeChange = (e) => {
console.log((addrtype[e.target.value]))
gender =addrtype[e.target.value]
}
console.log(gender)
What I'm looking for is reading the value gender which is actually undefined
Any help is welcome,
Best Regards
If you wish to have a 'variable' and update it based on an action, and then use the updated value elsewhere, you should use state
const [gender, setGender] = useState('');
const handleAddrTypeChange = (e) => {
console.log((addrtype[e.target.value]))
setGender(addrtype[e.target.value])
}
console.log(gender)
updating a components state will rerender the component with the new value for gender. Setting a variable like in your example will not rerender the component
Related
I have a TSX file, with a state including:
tickets: Ticket[],
I now want to change one specific element inside the array, and reset the state, my idea:
onClick = (ticket: Ticket, i: number) => {
var newTitle = window.prompt('hello')
ticket.title = newTitle ? newTitle : ticket.title
var tickets = [this.state.tickets]
tickets[i] = ticket
// set state
}
Besides the usual "OBject could be undefined" errors, I'm mainly getting stuck at:
Type 'Ticket' is missing the following properties from type 'Ticket[]': length, pop, push, concat, and 28 more. TS2740
It's as if they still consider tickets[i] to be of type Tickets[]. (I've done other checks and that seems to be the problem).
Do you know why this is the case? And how can still achieve my goal?
Thank you
There's a lot that's wrong here including multiple mutations of state.
Array of Arrays
The particular error that you've posted:
Type 'Ticket' is missing the following properties from type 'Ticket[]': length, pop, push, concat, and 25 more.
Is caused by this line:
var tickets = [this.state.tickets]
You are taking the array of tickets from state and putting it into an array. This variable tickets is an array with one element where that element is the array from your state. In typescript terms, it is [Ticket[]] or Ticket[][]. So each element of that array should be Ticket[] instead of Ticket. When you try to set an element with a Ticket then you get an error that it should be Ticket[].
State Mutations
As a rule of thumb, don't mutate anything in React if you aren't certain that it's safe. Just setting ticket.title is an illegal mutation of state which will prevent your app from re-rendering properly. The Ticket object that is passed to onClick is (presumably) the same object as the one in your state so you cannot mutate it.
Instead, we use array.map (which creates a copy of the array) to either return the same Ticket object or a copied one if we are changing it. We don't actually need the ticket as an argument. If the tickets have some unique property like an id then you could also pass just the ticket and not i.
onClick = (i: number) => {
const newTitle = window.prompt("hello");
if (newTitle) {
this.setState((prevState) => ({
tickets: prevState.tickets.map((ticket, index) =>
index === i ? { ...ticket, title: newTitle } : ticket
)
}));
}
};
I've a content type called continent. Which we the name suggests contains all the information about each continents. Strapi already created API endpoints for me like
continents/:id
But I want to search the continent by it's name since the general user won't be able to search by id
I've created the endpoint
continents/:continent_name
I've also created custom controller following documentation
const { sanitizeEntity } =
requiree('strapi-utils');
module.exports = {
async findOne(ctx) {
const { continent_name } = ctx.params;
const entity = await
strapi.services.continent.findOne({
continent_name
});
return sanitizeEntity(entity, { model:
continents });
And also exposed the API to public
But doesn't seem to anything
Just returns error
How am I supposed to do it
For your use case, you don't need to extend the model controller. You can just pass the continent name as a query param . For example, your url could be something like base_url/continent?continent_name=Asia.
For the code mentioned in the question, there is an issue, the model name should be strapi.models.continent and not continents. Also in the first line requiree('strapi-utils'), you have an extra e in the require. I am assuming that was just a typo.
I have a custom entity field placed inside NetSuite, now I have to source the value of this field to my Reference Checkout as I'll use the value as a condition for which payment method to show on the shop.
Any ideas how to do this? I've searched the SuiteAnswers and got no significant help there.
Thank you!
I've looked into using view.model.get('customfield ID here') but it has not worked. I've also already defined the field on models.js. Just not sure if I placed it properly.
Render function of Order Wizard Payment Method Selector
, render: function()
{
if (this.wizard.hidePayment())
{
this.$el.empty();
this.trigger('change_label_continue');
return;
}
if (!this.selectedModule)
{
var selected_payment = this.model.get('paymentmethods').findWhere({primary: true})
, selected_type;
var creditlevelhold = this.wizard.model.get('creditlevelhold'); < -- this is the custom field
console.log(creditlevelhold);
if(selected_payment){
selected_type = selected_payment.get('type');
}
else if(this.wizard.options.profile.get('paymentterms') && creditlevelhold === ''){
selected_type = 'invoice';
}
this.setModuleByType(selected_type)
Should be available like:
this.wizard.model.get('options')['custbodyxxx']
I'm facing a silly issue of the default value not being rendered in the form.
In my app, when the user is logged in, a form will be auto-filled with some of the details as it will fetch the data from the stored user information passed to my component through props.
In that case, my already selected 'Gender' i.e. the default value is not getting displayed when the component is rendered.
At the same time, when I passing the same value as hard-coded, it works perfectly fine.
I'm receiving the 'defaultValue' in 'renderGenderDropDown' as 'Male'(same as I stored in myValue const).
But, myValue const works, defaultValue doesn't.
And yes, my component is used in multiple other components and works perfectly fine. It basically, renders '' from 'React'.
What do I need to fix this?
Code:
renderGender() {
const { options, data } = this.props;
const gender = get(data, 'gender');
const defaultValue = gender ? capitalize(gender) : gender;
const fieldName = 'gender';
return this.renderGenderDropDown(fieldName, defaultValue, prefixOptions);
}
renderGenderDropDown(fieldName, defaultValue, options) {
const { configuration, id, validations } = this.props;
const myValue = 'Male';
return <AppDropDown
label={getLabel(fieldName, configuration, validations, 'gender')}
options={dropdownOptions}
defaultValue={myValue}
//defaultValue={defaultValue}
key={fieldName}
className={fieldName}
disabled={false}
id={id}
onChange={this.onGenderChange(this[fieldName])}
/>
}
In Javascript, there isnt a native capitalize() . This is probably returning back undefined instead of a string. Try this to capitalize the first letter in the string.
gender.charAt(0).toUpperCase() + gender.substr(1)
I am building my first sailsjs and nodejs application, and it great :)
My situation, I have about 100 tables with the same stucture, I would like to decide "on the fly" which table to load.
my first thought was use somehow a dynamic class names. But I dont know how to do this with nodejs, maybe some one have an idea.
So I would create 100 "modelName".js files in my models folder.
I can use this in browser
window["fileName"].find()....
But I don't have any window object in nodejs
Second idea was to pass the tableName to the model, the problem is, I have to reinit the model, don't know how.
Any solutions?
Found a solution
var modelName = req.param('p');
this[modelName].find()...
Own answer by author is correct, but I will add something just for people who will use it in the future - you can get modelName from req.options.model when you are using Blueprints.
Unfortunately you can't use this[modelName] as option is giving you model name starting with small letter, so first you have to upper case first letter with e.g. var modelName = req.options.model.charAt(0).toUpperCase() + req.options.model.slice(1);
and then you are free to use this[modelName].whateverYouNeed
I used it for generic policy to let user editing only his own group elements.
var modelName = req.options.model.charAt(0).toUpperCase() + req.options.model.slice(1)
var elementID = null
if (req.params.id) { // To handle DELETE, PUT
elementID = req.params.id
}
if (req.body.id) { // To handle POST
elementID = req.body.id
}
this[modelName].findOne({
id: elementID
}).exec(function(err, contextElement) {
if(err) {
return res.serverError(err)
}
if(contextElement.group=== req.user.group.id) {
sails.log('accessing own: ' + modelName)
return next()
}
else {
return res.forbidden('Tried to access not owned object')
}
})
An alternative:
sails.models[Model].findOne({...})
Make sure to have your "Model" name as string in lowercase. It works like accessing a property inside an object
Another option that worked for me:
var modelName = "User";
global[modelName].find()....