How to get state name from function argument when using setState in React [duplicate] - javascript

This question already has answers here:
Add a property to a JavaScript object using a variable as the name? [duplicate]
(14 answers)
JavaScript property access: dot notation vs. brackets?
(17 answers)
Closed 11 days ago.
I have the following state in my React Component:
class App extends Component {
constructor(props) {
super(props);
this.state = {
temperatureBedroom: 22.0,
temperatureLivingRoom: 23.0,
...
Now, I would like to update the state with the this.setState function.
The most straightforward way to do it is to just use the following code:
increaseTemp = () => {
let increment = 0.5;
this.setState({
temperatureBedroom: this.state.temperatureBedroom + increment
});
...
However, the problem is that with this approach I have to define a new (handler) function for each of the states (variables), i.e., as in my example -- rooms, for which I'd like to set a new value (temperature).
I was wondering if there is a more efficient way in React to address this issue.
The desired outcome would be to have something like that for the Buttons control:
<Button
variant="outline-secondary"
onClick={() =>
this.increaseTemp("temperatureBedroom")
}
>
+
</Button>
and I would like to use this argument like that:
increaseTemp = (roomName) => {
let increment = 0.5;
this.setState({
roomName: this.state.roomName + increment
});
...
The documentation doesn't mention a simple way to do it. It shows an example of writing separate handler functions for each state variable, see e.g.: https://beta.reactjs.org/learn/updating-objects-in-state
I have found similar questions, but some other aspects of the setState are discussed there, none of them addresses specifically the issue I would like to resolve:
How to setState from function parameter in React
Using function name as parameter of setState method?
Maybe I could try using a function as a setState parameter, but I am not sure if it helps with my problem: https://medium.com/#wisecobbler/using-a-function-in-setstate-instead-of-an-object-1f5cfd6e55d1
I would appreciated any suggestions how to avoid writing redundant handler functions.

Related

Difference between these Two syntaxes in React [duplicate]

This question already has answers here:
What's the difference between passing a value and passing a callback in a React setState hook function?
(2 answers)
Closed 4 months ago.
I'm not an expert in React Js and want to know the difference between these two syntaxes in the ES6 syntax.
const items = array.map(thing => <p key={thing}>{thing}</p>)
function addItem(){
setArray(previtems => { return [...previtems, `Thing ${array.length + 1}`]});
}
and
const items = array.map(thing => <p key={thing}>{thing}</p>)
function addItem(){
setArray([...items, `Thing ${array.length + 1}`]);
}
The first one is functional setState. It gives guarantee that the value of prevItems will be the most updated one. This pattern is to be used whenever next state depends on the previous state.

Typescript syntax: calling a function with < > [duplicate]

This question already has answers here:
Rules for the use of angle brackets in TypeScript
(2 answers)
Closed 3 years ago.
I have just seen a piece of code for React that has a syntax I have never seen before. I haven't been able to find what it actualy is. Can someone, please, explain what calling a function with <> instead of () does?
const ConfirmationServiceContext = React.createContext<
// we will pass the openning dialog function directly to consumers
(options: ConfirmationOptions) => Promise<void>
>(Promise.reject);
The piece of code is from here
This is actually Typescript type firm for an async lamda.
React.createContext<(options: ConfirmationOptions) => Promise<void>>(Promise.reject);
React.createContext is a Generic type, the < and > is how we pass the concrete type we're going to use in this instance. Here we're passing an inline function that gets a ConfirmationOptions object and returns a Promise whose value is void

What does ...this.somefunction() (invocation of a class function preceded by ellipsis) do in javascript in an object assignment? [duplicate]

This question already has answers here:
What are these three dots in React doing?
(23 answers)
Closed 3 years ago.
Trying to understand a code snippet. What does ...this.savedSettings() do in the following snippet. afaik, ellipsis is used for destructuring and to pass variables to a function (spread syntax)
constructor(props) {
super(props);
this.state = {
page: 'dashboard',
...this.savedSettings(), // THIS LINE
setPage: this.setPage,
};
}
savedSettings() {
if(noData) {
return {page: 'settings', firstVisit: true};
}
return {};
}
PS: I understand that there is a similar question here as mentioned by mod. I did refer to the same before putting this one out. Goes without saying, the spread syntax is subtle and that question was a generic, albeit well answered, question on applying it on an object like props in a React component. It was not immediately clear to me how to apply that here.
This question is more generic as to applying spread syntax against a JS function call. IMHO for someone not very experienced/on the way of being experienced, the subtle difference can be confusing and a question/snippet like this can be profitable.
That said, I've answered this myself. While SE runs promos to ask questions, they should highlight the fact that it risks reputation. Thanks for the downvotes.
This is in fact used as spread syntax. The syntax is applied to the returned object. It merges the given object (this.state with the object returned by the function this.savedSettings(). Resulting in this.state being assigned with
// if noData is true
{
page: 'settings', // MERGED/OVERWRITTEN
firstVisit: true, // MERGED/ADDED
setPage: this.setPage,
};
or
// if noData is false
{
page: 'dashboard',
setPage: this.setPage,
};

What is the difference between var {todo}= require("./models/todo"); and var todo=require("./models/todo"); [duplicate]

This question already has answers here:
Curly brackets (braces) in Node.js 'require' statement
(2 answers)
Closed 3 years ago.
I am trying to load a todo model from my todo class and I have two options. The first one is
var {todo}= require("./models/todo");
and second one is
var todo=require("./models/todo");
I am confused which is what.
The first one is a destructuring assignment. It means "take an object from "models/todo" and assign its property "todo" to my local variable "todo". If it contains no such property, you'll get undefined assigned to the variable.
For example this if is your model
module.exports = {
toLower: obj => {
},
streamIdea: async (idea) => {
}
}
if you're doing this
const model = require('mymodel');
then you have to call your functions like this,
model.toLower()
which means you're importing everything and calling it by function name
and if you're importing like this:
const { toLower } = require('mymodel');
it means you're only importing toLower from this model now you can just call it like this
toLower();
without need of model.

Javascript API syntax help - const { uport, MNID } [duplicate]

This question already has answers here:
What is the difference between const and const {} in JavaScript
(4 answers)
Closed 4 years ago.
So while I was making my react native app, I tried to use an API from
https://github.com/uport-project/react-native-uport-connect and there is a syntax that I've yet to understand.
May I know what does const { uport, MNID } mean from this code
import configureUportConnect from 'react-native-uport-connect'
const { uport, MNID } = configureUportConnect({
appName: 'uPort Demo',
appAddress: '2oeXufHGDpU51bfKBsZDdu7Je9weJ3r7sVG',
privateKey:'<PRIVATE_KEY>',
})
Im quite new to this and this code is placed on a seperate js file and im trying to export const { uport, MNID } so I could use it in my Components and im not sure if it's a variable, object or some js syntax. Thank you!
This is called destructuring, and it means you are assigning your variables, not to the object that the function returns, but to the individual properties of that object, specifically the properties at the keys uport and MNID. The alternative syntax would be to say const variableName = // etc... and then you would access the properties like: variableName.uport.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#Object_destructuring

Categories