Trying to check if input is an array React Javascript using JSON.parse() throws an error if it's not [duplicate] - javascript

This question already has answers here:
How to check if a string is a valid JSON string?
(27 answers)
Closed 2 years ago.
I am trying to check if the value in the input is Array.
This is working great if the input is an array, but if the input is not an array, I get JSON errors: Uncaught SyntaxError: Unexpected token s in JSON at position 0
Any other solutions that won't throw errors and keep the code working so if it's a different input I can render something else?
function App() {
const [input, setinput] = React.useState("");
const handleSubmit = (event) => {
event.preventDefault();
let parsed = JSON.parse(input);
let condition = Array.isArray(parsed);
if(condition === true){
console.log('working')
}

Array.isArray(input)
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray
Scroll down to examples.

Related

Use object destructuring prefer-destructuring [duplicate]

This question already has answers here:
How to fix Eslint error "prefer-destructuring"?
(3 answers)
Closed 11 months ago.
I am codding first time on Vue.js and I have problem. Can you describe me the solution or problem.enter image description here
const { data } = await ...
Use this in 108 and 97 lines.
Your promise object has a data element. Currently, you are accessing your data element using dot (.) syntax. ( Your promise object.data is returning data).
You can use object destructuring to directly access the data element from inside your promise object
const { data } = (await this.$api.auth.sighIN({
email: this.email,
password: this.form.password,
}));

concatenating 2 arrays unexpected result [duplicate]

This question already has answers here:
React hooks stale state
(1 answer)
State not updating when using React state hook within setInterval
(14 answers)
Wrong React hooks behaviour with event listener
(9 answers)
Closed 1 year ago.
I am trying to update my array state with a list of records I am getting from an API, I am trying it as follows:
const [record, setRecord] = useState([])
const addRecords= async ()=>{
const apiResult = await apicall()
setRecord(record.length ? [...apiResult, ...record] : apiResult)
}
however every time the api is called is overwritting my 'record' with the last items added from the api instead of putting them together.
I also tried using .concat() with same result
const addRecords=async()=>{
const apiResult = await apicall()
setRecord(record.concat(apiResult ? apiResult:[])
}
there is sth here I am not managing to understand, hope someone can clarify what can it be.
I think you want to use a function in your setter to get your previous value (I dont understand enough to give you the reason why, but I think it has something to do with your record being a frame or two out of date)
const addRecords=async()=>{
const apiResult = await apicall()
//prevRecord is more recent than record (I think)
setRecord(prevRecord=>prevRecord.concat(apiResult || [])
}

Javascript: Create dictionary from array of strings [duplicate]

This question already has answers here:
ECMAScript 6 arrow function that returns an object
(6 answers)
Closed 3 years ago.
I have an array of strings that I get from an endpoint and I need to convert it to key-value pairs for the frontend to display them correctly. I have tried different concepts such as reduce and map but have not been able to get it working successfully. I assume it might be one-liner for someone familiar with FE but has taken forever for a BE person like me.
Here is what I have tried:
var input = ['quiz1', 'quiz2'];
const mapping = input.map(x => {"id":x, "label":x};);
console.log(mapping);
I am expecting an output of the format
[{"id":"quiz1", "label":"quiz1"}, {"id":"quiz2", "label":"quiz2"}]
Thanks for looking!
It's simply two syntax errors:
var input = ['quiz1', 'quiz2'];
const mapping = input.map(x => ({"id":x, "label":x}));
console.log(mapping);
Firstly, no semicolon in a un-braced arrow function body.
This is invalid: (() => 3;). This is valid: (() => 3).
Secondly, wrap return obj in ().
This is invalid: () => {x: 3}. This is valid: () => ({x: 3}).

javascript array filter shows type error [duplicate]

This question already has answers here:
Accessing an object property with a dynamically-computed name
(19 answers)
Closed 5 years ago.
I want to get the value from array. It shows Type error. The code is
var user = "username6";
var result = categories.filter(x => x.user)[0].user;
TypeError: Cannot read property 'user' of undefined
But it work in
var result = categories.filter(x => x.username6)[0].username6;
I want to give the "username6" variable in user. And execute
var result = categories.filter(x => x.user)[0].user;
How it possible? Please help me?
You should use the brackets notation instead of the dot notation
var user = "username6";
var result = categories.filter(x => x[user])[0][user];

Custom Number.prototype working with variable but NOT working directly with number [duplicate]

This question already has answers here:
Calling member function of number literal
(3 answers)
Closed 6 years ago.
I have included custom Number.prototype in my JS as below:
Number.prototype.isBetween = function (first, last) {
return (first < last ? this >= first && this <= last : this >= last && this <= first);
};
This is working as expected with below code:
var a = 40;
a.isBetween(10,50)
Result :
true
But when i try to execute as below, it is throwing an error:
40.isBetween(10,50)
Result :
Uncaught SyntaxError: Invalid or unexpected token
How to make this(40.isBetween(10,50)) work?
You can wrap the number in parentheses to solve this.
(40).isBetween(10,50)
// => true
Without the parentheses, there is ambiguity in the grammar that the language parser intentionally avoids by throwing an error.
For details and other solutions, see answers to this question: Calling the toFixed method on a number literal

Categories