0

I have a react app where I am making a post call to an api. My post sends a key value object that is converted to json using JSON.stringify. This properties represent the fields in a database and values are numeric in some cases. My problem is that I get a 400 error.

I suspect this is because the json object I am passing looks like this:

let data =
{
"field1": "value1",
"field2": "value2",
"count": "47"
}

I'm setting these property values from state like so:

let data =
{
"field1": state.value1,
"field2": state.value2,
"count": state.value3
}

However, count in my database table where the object is being posted to is a number field.

To test this theory, I created a hardcoded object that looks like the following and when I post that it works just fine:

let data =
{
"field1": "value1",
"field2": "value2",
"count": 47
}

Javascript is not typed so how can I create an object that looks like the one above where non string values are not enclosed in quotes?

1
  • The issue is that the value is a string, not an integer Commented Mar 20, 2020 at 6:41

1 Answer 1

1

You can cast a String to Integer in Javascript in a number of ways.

Method 1:

const stringAsNumber = "0";
const castedString = +stringAsNumber;
console.log(castedString); // 0
console.log(typeof castedString); // "number"

Method 2:

const stringAsNumber = "0";
const castedString = parseInt(stringAsNumber);
console.log(castedString); // 0
console.log(typeof castedString); // "number"

So in your case, do the following:

let data = {
    "field1": state.value1,
    "field2": state.value2,
    "count": +state.value3
}

Note: If you use + or parseInt on a string that cannot be a number then it will return NaN

Sign up to request clarification or add additional context in comments.

1 Comment

Yes! Haven't worked with javascript in a while. That's what I needed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.