Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

React get value from State

Complete beginner to React. I have a backend API that I am trying to send requests to using Axios. I have a box with numbers like so:

const [input, setInput] = useState(0);
const [input2, setInput2] = useState(0);

        <div>
            <label htmlFor="num1">Number 1: </label>
                <input type="string" id="num1" name="num1" value={input} onInput={e => setInput(e.target.value)}/>
        </div>
        <br/>
        <div>
            <label htmlFor="num2">Number 2: </label>
            <input type="string" id="num2" name="num2"value={input2} onInput={e => setInput2(e.target.value)}/>
        </div>

This captures any value in these inputs.

    console.log({input})
    console.log({input2})

Logging these values shows the integer I put in there. However, when I try to access these values in an Axios request, it all goes wrong.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

    const response = await     axios
        .get("http://localhost:8080/service/", {
            params: {
                num1: {input},
                num2: ({input2})
            }
        })

My back end throws this exception:

java.lang.NumberFormatException: For input string: "{"input":0}"]

I would just like to pass the zero to my request param, is this possible? If so, how to achieve this? I have tried parsing it in various different ways but nothing works. The backend only takes a number in those parameters.

Best regards.

>Solution :

You don’t need to wrap your state in curly brackets. Where you write {input}, javascript automatically creates a new object {input: inputValue} instead of returning the value of your input variable.

Just change your code to this:

    const response = await     axios
    .get("http://localhost:8080/service/", {
        params: {
            num1: input,
            num2: input2
        }
    })
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading