How do I add new values to state using Typescript? - reactjs

you need to add new values to the array, I can't understand what the problem is.
When you click on a checkbox, you need to get the id of this checkbox and write it to the array of answers for the corresponding question
type Result = number;
interface Answer {
result: Result[];
}
const answers: Answer[] = [];
questions.forEach(() => {
answers.push({
result: [],
});
});
const [currentAnswer, setNewAnswer] = useState<Answer[]>(answers)
const handleChange = (e:React.ChangeEvent<HTMLInputElement>) =>{
// console.log(typeof(currentAnswer),currentAnswer);
if(e.target.checked){
console.log(currentAnswer[currentQuestion].result.push(Number(e.target.id)));
setNewAnswer(
currentAnswer[currentQuestion].result.push(Number(e.target.id) // ERROR HERE
)
...
I got error
const currentAnswer: Answer[]
// Argument of type 'number' is not assignable to parameter of type 'SetStateAction<Answer[]>'

should use .concat() in this situation to return new array
.push() will only return new length which is number and incompatible with the type you make.
setNewAnswer(
currentAnswer[currentQuestion].result.concat(Number(e.target.id)) // ERROR HERE
)

To expand on Mic Fung's answer, push mutates the existing array and doesn't return the new array.
const myArray = [1, 2, 3]
myArray.push(4) // returns 4, which is the new array length
console.log(myArray) // [1, 2, 3, 4]
concat doesn't mutate the existing array, but instead returns a new array
const myArray = [1, 2, 3]
const myNewArray = myArray.concat(4)
console.log(myNewArray) // [1, 2, 3, 4]
console.log(myArray) // [1, 2, 3]
When working with React, you should avoid directly mutating the state. Instead, create new values and pass them to the setState function. This is why functions like concat are preferred over ones like push, as they avoid the mutation.

Related

How can I do to change the first element of an array using useState?

here is my code :
const [myArray, setMyArray] = useState([0, 0])
And I would like to change only the first element to get myArray = [3, 0]
How can I do to do that ?
Thank you very much !
You can do in this way. First copy the state then do modification and set it again
const handleChange = () => {
let copyState = [...myArray]
copyState[0] = 3
setMyArray(copyState)
}
You can call setMyArray method passing a function as argument.
The function destructures the myArray into el1 and el2 and recreates a new array where the first element is equal to 3:
setMyArray((myArray) => {
const [el1, el2] = myArray;
return [3, el2]
});
or simplified
setMyArray(([el1, el2]) => [3, el2]);

How to use Array.prototype.map ()?

Hi I have a quick question. I am working on a JavaScript Project and am needing to use.
const array = [1, 4, 9, 16];
const map = array.map(x => x 2);
console.log(map);
Error: missing ) after argument list
I am not able to understand what you want to achieve with that code but if you want to resolve that issue you are missing the operator in between the x [] 2 --> insert the operator like (+,-,/,*) as per your need.
const array = [1, 4, 9, 16];
const map = array.map(x => x *2);
console.log(map);
You have an error here.
const map = array.map(x => x 2);
Change it as follow.
const map = array.map(x => x * x);
And don't use map as a variable name. It's confusing.

Extract array inside Objects

I am using ReactJS.
I have a JSON:
{
"randomNum1": [
1,
2,
3,
4
],
"randomNum2": [
5,
6,
7,
8
]
}
What I wanted to do is to get the array of randomNum1 and randomNum2. This is what I did:
for(let i = 0; i<data.randomNum1.length; i++)
and I get this error:
Cannot read property 'length' of undefined
The reason why I did that is because when I do a console.log(data.randomNum1) I am able to see the array: [array][1]
Is it because it's still an Object which is why .length is not allowed? If so, how can I get the values of those numbers and store it in an array?
[1]: https://i.stack.imgur.com/nLbdA.png
let allValues=[]
let the_json_object={
"randomNum1": [
1,
2,
3,
4
],
"randomNum2": [
5,
6,
7,
8
]
}
const keys = Object.keys(the_json_object);
const values = Object.values(the_json_object);
let Key_len = keys.length;
for(i=0;i<Key_len;i++){
let len = values[i].length;
for(j=0;j<len;j++)
{
if(values[i][j])
{
allValues.push(values[i][j])
}
}
}
//allValues contains all the values from all arrays.
Your data object is probably undefined at the moment you are entering the loop.
The reason you see it on console.log is because objects are passed by reference. When you console.log the object and then click to see his properties you get the updated object. If you'll do console.log(JSON.stringify(data)) you will see the object is probably empty.
Please provide more code in order to understand the issue here.

why add curly braces to the argument 'people' here [duplicate]

I have been reading about Destructuring assignment introduced in ES6.
What is the purpose of this syntax, why was it introduced, and what are some examples of how it might be used in practice?
What is destructuring assignment ?
The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.
- MDN
Advantages
A. Makes code concise and more readable.
B. We can easily avoid repeated destructing expression.
Some use cases
1. To get values in variable from Objects,array
let obj = { 'a': 1,'b': {'b1': '1.1'}}
let {a,b,b:{b1}} = obj
console.log('a--> ' + a, '\nb--> ', b, '\nb1---> ', b1)
let obj2 = { foo: 'foo' };
let { foo: newVarName } = obj2;
console.log(newVarName);
let arr = [1, 2, 3, 4, 5]
let [first, second, ...rest] = arr
console.log(first, '\n', second, '\n', rest)
// Nested extraction is possible too:
let obj3 = { foo: { bar: 'bar' } };
let { foo: { bar } } = obj3;
console.log(bar);
2. To combine an array at any place with another array.
let arr = [2,3,4,5]
let newArr = [0,1,...arr,6,7]
console.log(newArr)
3. To change only desired property in an object
let arr = [{a:1, b:2, c:3},{a:4, b:5, c:6},{a:7, b:8, c:9}]
let op = arr.map( ( {a,...rest}, index) => ({...rest,a:index+10}))
console.log(op)
4. To create a shallow copy of objects
let obj = {a:1,b:2,c:3}
let newObj = {...obj}
newObj.a = 'new Obj a'
console.log('Original Object', obj)
console.log('Shallow copied Object', newObj)
5. To extract values from parameters into standalone variables
// Object destructuring:
const fn = ({ prop }) => {
console.log(prop);
};
fn({ prop: 'foo' });
console.log('------------------');
// Array destructuring:
const fn2 = ([item1, item2]) => {
console.log(item1);
console.log(item2);
};
fn2(['bar', 'baz']);
console.log('------------------');
// Assigning default values to destructured properties:
const fn3 = ({ foo="defaultFooVal", bar }) => {
console.log(foo, bar);
};
fn3({ bar: 'bar' });
6. To get dynamic keys value from object
let obj = {a:1,b:2,c:3}
let key = 'c'
let {[key]:value} = obj
console.log(value)
7. To build an object from other object with some default values
let obj = {a:1,b:2,c:3}
let newObj = (({d=4,...rest} = obj), {d,...rest})
console.log(newObj)
8. To swap values
const b = [1, 2, 3, 4];
[b[0], b[2]] = [b[2], b[0]]; // swap index 0 and 2
console.log(b);
9. To get a subset of an object
9.1 subset of an object:
const obj = {a:1, b:2, c:3},
subset = (({a, c}) => ({a, c}))(obj); // credit to Ivan N for this function
console.log(subset);
9.2 To get a subset of an object using comma operator and destructuring:
const object = { a: 5, b: 6, c: 7 };
const picked = ({a,c}=object, {a,c})
console.log(picked); // { a: 5, c: 7 }
10. To do array to object conversion:
const arr = ["2019", "09", "02"],
date = (([year, day, month]) => ({year, month, day}))(arr);
console.log(date);
11. To set default values in function. (Read this answer for more info )
function someName(element, input,settings={i:"#1d252c", i2:"#fff",...input}){
console.log(settings.i)
console.log(settings.i2)
}
someName('hello', {i:'#123'})
someName('hello', {i2:'#123'})
12. To get properties such as length from an array, function name, number of arguments etc.
let arr = [1,2,3,4,5];
let {length} = arr;
console.log(length);
let func = function dummyFunc(a,b,c) {
return 'A B and C';
}
let {name, length:funcLen} = func;
console.log(name, funcLen);
It is something like what you have can be extracted with the same variable name
The destructuring assignment is a JavaScript expression that makes it possible to unpack values from arrays or properties from objects into distinct variables. Let's get the month values from an array using destructuring assignment
var [one, two, three] = ['orange', 'mango', 'banana'];
console.log(one); // "orange"
console.log(two); // "mango"
console.log(three); // "banana"
and you can get user properties of an object using destructuring assignment,
var {name, age} = {name: 'John', age: 32};
console.log(name); // John
console.log(age); // 32
The De-structured assignment of Javascript is probably an inspiration drawn from Perl language.
This facilitates reuse by avoid writing getter methods or wrapper functions.
One best example that I found very helpful in particular was on reusing functions that return more data than what is required.
If there is a function that returns a list or an array or a json, and we are interested in only the first item of the list or array or json,
then we can simply use the de-structured assignment instead of writing a new wrapper function to extract the interesting data item.

RxJS create new Observable "Array" from and static array in typescript

I am able to create observable from an array but its type is Observable<number> not Observable<number[]>
getUsers(ids: string[]): Observable<number[]> {
const arraySource = Observable.from([1, 2, 3, 4, 5]);
//output: 1,2,3,4,5
const subscribe = arraySource.subscribe(val => console.log(val));
let returnObserable = Observable.from([1, 2, 3, 4, 5]);
return returnObserable; //error at this line, because of the return type
}
Is there any other way to create observable other than from ?
If you want the entire array to be emitted as a single emissions use Observable.of instead:
const arraySource = Observable.of([1, 2, 3, 4, 5]);
Observable.from iterates the array and emits each item separately while Observable.of takes it as without any further logic.
Alternatively, you could also nest two arrays but that's probably too confusing:
const arraySource = Observable.from([[1, 2, 3, 4, 5]]);

Resources