mayorsanmayor
mayorsanmayor

Reputation: 2988

encodeURIComponent in React

I have a react function returning a promise from axios, and I need to encode an equation type string is being passed to it.

const { equation } = this.state;
axios.post(`${this.state.rootUrl}/integrate`, { equation }).then(some other code)

I want to encode the string equation before passing it to the API for a query.

I have tried the following but it didn't work.

axios.post(`${this.state.rootUrl}/integrate`, { encodeURIComponent(equation) })

I also tried this:

const { equation } = this.state;
const { test } = encodeURIComponent(equation);
axios.post(`${this.state.rootUrl}/integrate`, { test }).then(some other code)

This also didn't work.

Here's the full code of the function where I'm trying use this:

handleSubmit = (e) => {
    e.preventDefault();
    const { equation } = this.state;
    // const { test } = encodeURIComponent(equation);
    axios.post(`${this.state.rootUrl}/integrate`, { equation })
      .then((response) => {
        const data = response.data;
        this.setState({ data: data });
        console.log(equation);
        if (data != null) {
          this.setState({input: data.response[0]});
        }
    }
  }

Upvotes: 1

Views: 15906

Answers (2)

Joe Clay
Joe Clay

Reputation: 35797

In your original example, you're using the shorthand syntax for setting object properties - the following two lines of code are equivalent:

{ equation }
{ equation: equation }

Your second two examples don't do the same thing! In example two, you're trying to use the shorthand with a method call, which won't work. In example three, you're trying to destructure the return value of encodeURIComponent(equation), which also won't work (it returns a string).

Fawaz's first example almost works, but there's a subtle difference in behavior - because they've named the variable test, the key of the object being passed to Axios will also be test. Remember, these are equivalent:

{ test }
{ test: test }

Presumably, your API is expecting something called equation, not test, so this won't work.

To get the right behavior, you should make sure the object you're passing has the right key:

const test = encodeURIComponent(equation);
axios.post(`${this.state.rootUrl}/integrate`, { equation: test })

// or

axios.post(`${this.state.rootUrl}/integrate`, { equation: encodeURIComponent(equation) })

Upvotes: 5

Fawaz
Fawaz

Reputation: 3560

There seems an issue in using the shorthand. Try like this :

const test = encodeURIComponent(equation); // no braces here
axios.post(`${this.state.rootUrl}/integrate`, { test }).then(some other code)

or

axios.post(`${this.state.rootUrl}/integrate`, { test: encodeURIComponent(equation) })

Upvotes: 1

Related Questions